英文:
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;
}
}
} catch (Exception e) {
// 处理异常
}
当我尝试运行时,出现以下错误: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
怎样才是最佳实现方式?
英文:
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 ?
答案1
得分: 1
使用XMLOutputFactory
来创建输出流
XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader dataXML = factory.createXMLStreamReader(new FileReader(path));
XMLStreamWriter dataWXML = outFactory.createXMLStreamWriter(new FileReader(otherPath));
// ...
}
请注意输出文件使用了另一个路径。
英文:
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
答案2
得分: 0
这一行是你的问题:
XMLStreamWriter dataWXML = (XMLStreamWriter) factory.createXMLStreamReader(new FileReader(path));
你不能简单地将一个XMLStreamReader强制转换为XMLStreamWriter。它们是不同的类,XMLStreamWriter并不继承自XMLStreamReader。
英文:
This line is your problem:
XMLStreamWriter dataWXML = (XMLStreamWriter) factory.createXMLStreamReader(new FileReader(path));
You simply cannot cast an XMLStreamReader to an XMLStreamWriter. They are separate classes and XMLStreamWriter does not extends from XMLStreamReader
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论