我有以下代码,用于使用Stax将XML文件的元素转换为String:
private static XMLStreamReader getReader(InputStream inputStream) throws XMLStreamException {
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty("javax.xml.stream.isValidating", false);
xmlInputFactory.setProperty("javax.xml.stream.supportDTD", false);
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
return xmlStreamReader;
}
private static String readElement(XMLStreamReader reader) throws XMLStreamException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
StAXSource source = new StAXSource(reader);
t.transform(source, new StreamResult(outputStream));
return outputStream.toString();
}
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream("c:\\temp\\test.xml");
XMLStreamReader xmlStreamReader = getReader(inputStream);
int count = 0;
while (xmlStreamReader.hasNext()) {
int eventType = xmlStreamReader.next();
if (eventType == XMLEvent.START_ELEMENT) {
String elementName = xmlStreamReader.getName().getLocalPart();
if (!elementName.toLowerCase().equals("element")) {
continue;
}
String productStr = readElement(xmlStreamReader);
System.out.println(productStr);
}
}
}
}
这适用于以下XML片段:
<testDoc>
<element>
<a>hello world</a>
<b>hello world again</b>
</element>
<element>
<a>foo</a>
<b>foo bar</b>
</element>
</testDoc>
但是,此片段存在问题,其中</element>
和<element>
位于同一行:
<testDoc>
<element>
<a>hello world</a>
<b>hello world again</b>
</element><element>
<a>foo</a>
<b>foo bar</b>
</element>
</testDoc>
在第二个例子中,它似乎只处理第一个元素而不是第二个元素。有什么想法吗?
更新
我使用以下代码:
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream("c:\\temp\\test.xml");
XMLStreamReader xmlStreamReader = getReader(inputStream);
int count = 0;
while (xmlStreamReader.hasNext()) {
int eventType = xmlStreamReader.getEventType();
if (eventType == XMLEvent.START_ELEMENT) {
String elementName = xmlStreamReader.getName().getLocalPart();
if (!elementName.toLowerCase().equals("element")) {
xmlStreamReader.next();
continue;
}
System.out.println(readElement(xmlStreamReader));
} else {
xmlStreamReader.next();
}
}
}
答案 0 :(得分:2)
对我来说看起来像个错误。你没有说你正在使用哪个Stax解析器:其中一些非常有绳索。 Woodstox是最可靠的。