Skip to content
Advertisement

Java how to use XMLStreamReader and XMLStreamWriter in the same method

I use XMLStreamReader to read xml file. I want to copy this actual file and add somes nodes in this file :

XMLInputFactory factory = XMLInputFactory.newInstance();
    
    try {
        XMLStreamReader dataXML = factory.createXMLStreamReader(new FileReader(path));
        XMLStreamWriter dataWXML = (XMLStreamWriter) factory.createXMLStreamReader(new FileReader(path));
        
        while (dataXML.hasNext())
        {
            int type = dataXML.next();
            switch(type)
            {
                case XMLStreamReader.START_ELEMENT:
                    
                     dataWXML.writeStartElement("apple");
                        
                    break;
            }

        }

When I try to run I have this error : Exception in thread "main" java.lang.ClassCastException: class com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl cannot be cast to class javax.xml.stream.XMLStreamWriter

What is the best way to do that ?

Advertisement

Answer

Use an XMLOutputFacotry instead to create the output stream

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
try {
    XMLStreamReader dataXML = factory.createXMLStreamReader(new FileReader(path));
    XMLStreamWriter dataWXML = factory.createXMLStreamWriter(new FileReader(otherPath));
    ...
}
    
       

Note the use of another path for the output file

Advertisement