Java 如何在同一个方法中使用 XMLStreamReader 和 XMLStreamWriter

Java how to use XMLStreamReader and XMLStreamWriter in the same method

我使用 XMLStreamReader 读取 xml 文件。我想复制这个实际文件并在此文件中添加一些节点:

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;
            }

        }

当我尝试 运行 时出现此错误: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

最好的方法是什么?

改用 XMLOutputFacotry 来创建输出流

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

注意输出文件使用另一个路径

这一行是你的问题:

    XMLStreamWriter dataWXML = (XMLStreamWriter) factory.createXMLStreamReader(new FileReader(path));

您根本无法将 XMLStreamReader 转换为 XMLStreamWriter。它们是独立的 类 并且 XMLStreamWriter 不从 XMLStreamReader

扩展