Reputation: 497
I have the following code for converting the elements of an XML file into a String using Stax:
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);
}
}
}
}
This works fine on the following XML fragment:
<testDoc>
<element>
<a>hello world</a>
<b>hello world again</b>
</element>
<element>
<a>foo</a>
<b>foo bar</b>
</element>
</testDoc>
However, there are problems with this fragment where the </element>
and <element>
are on the same line:
<testDoc>
<element>
<a>hello world</a>
<b>hello world again</b>
</element><element>
<a>foo</a>
<b>foo bar</b>
</element>
</testDoc>
In the second example it only seems to process the first element and not the second one. Any ideas?
Update:
I got it to work with the following code:
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();
}
}
}
Upvotes: 2
Views: 1536
Reputation: 163458
Looks like a bug to me. You don't say which Stax parser you are using: some of them are pretty ropey. Woodstox is the most reliable.
Upvotes: 2