在拆分一个巨大的XML文件时,我看到了一个使用Stax和Transformer.transform()的非常好的解决方案。很好,但我看到一些标签丢失了。这是为什么?
带有Name ...的XML文件给出以下结果。在EVENT场合,元素标记被省略。
Element: <?xml version="1.0" encoding="UTF-8"?><car><name>car1</name></car> Element: <?xml version="1.0" encoding="UTF-8"?><name>car2</name> Element: <?xml version="1.0" encoding="UTF-8"?><car><name>car3</name></car> Element: <?xml version="1.0" encoding="UTF-8"?><name>car4</name>
我怎样才能获得正确的元素?这与变换(s,r)干扰输入流读取有关吗?
这是我的代码(我在很多地方看过,比如this one)。使用StringReader或FileReader时没有任何变化。
我期待这个:循环{advance to start-tag;访问该元素}我看到的是:第一个:元素+第二个:元素的部分+重复。
String testCars = "<root><car><name>car1</name></car><car><name>car2</name></car><car><name>car3</name></car><car><name>car4</name></car></root>";
String element = "car";
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(testCars));
streamReader.nextTag();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(streamReader.nextTag() == XMLStreamConstants.START_ELEMENT) {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
t.transform(new StAXSource(streamReader), result);
System.out.println("Element: " + writer.toString());
}
} catch (Exception e) { ... }
感谢Andreas,这是解决方案:
String testCars = "<root><car><name>car1</name></car><other><something>Unknown</something></other><car><name>car2</name></car></root>";
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(testCars));
streamReader.nextTag();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
streamReader.nextTag();
while ( streamReader.isStartElement() ||
( ! streamReader.hasNext() && streamReader.nextTag() == XMLStreamConstants.START_ELEMENT)) {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
t.transform(new StAXSource(streamReader), result);
System.out.println( "XmlElement: " + writer.toString());
}
} catch (Exception e) { ... }
输入是:
<root>
<car>
<name>car1</name>
</car>
<other>
<something>Unknown</something>
</other>
<car>
<name>car2</name>
</car>
</root>
输出是:
XmlElement: <?xml version="1.0" encoding="UTF-8"?><car><name>car1</name></car>
XmlElement: <?xml version="1.0" encoding="UTF-8"?><other><something>Unknown</something></other>
XmlElement: <?xml version="1.0" encoding="UTF-8"?><car><name>car2</name></car>