I'm reading a XML file same as below:
<ts>
<tr comment="" label="tr1">
<node order="1" label="" />
</tr>
</ts>
And I expected the below code prints out three e
on screen:
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader sr = factory.createXMLStreamReader(new FileReader("test.xml"));
while (sr.hasNext()) {
int eventType = sr.next();
if (eventType == XMLStreamReader.START_DOCUMENT) {
continue;
} else if (eventType == XMLStreamReader.END_ELEMENT) {
System.out.println("e");
} else if (eventType == XMLStreamReader.START_ELEMENT) {
System.out.println("s");
}
}
But it doesn't work! Any ideas on how I can resolve the issue?
Note: I think it is related to self-closed-tags, for example: <myTag id="1" />
I'm on Windows using JDK 1.7 and am getting the same results as Blaise Doughan:
s
s
s
e
e
e
I don't think it has to do with the <node order="1" label="" />
since the documentation states that:
NOTE: empty element (such as
<tag/>
) will be reported with two separate events: START_ELEMENT, END_ELEMENT - This preserves parsing equivalency of empty element to<tag></tag>
. This method will throw anIllegalStateException
if it is called afterhasNext()
returns false.
Long shot: maybe some other related code may be causing the weird behavior?
The code posted in your question produced the three e
for me which is expected. I'm using JDK 1.6 on the Mac.
Demo
You may want to try running the following code to see which end element event you are missing:
import java.io.FileReader;
import javax.xml.stream.*;
public class Demo {
public static void main(String[] args) throws Exception {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader sr = factory.createXMLStreamReader(new FileReader("test.xml"));
System.out.println(sr.getClass());
while (sr.hasNext()) {
int eventType = sr.next();
if (eventType == XMLStreamReader.START_DOCUMENT) {
continue;
} else if (eventType == XMLStreamReader.END_ELEMENT) {
System.out.println("End Element: " + sr.getLocalName());
} else if (eventType == XMLStreamReader.START_ELEMENT) {
System.out.println("Start Element: " + sr.getLocalName());
}
}
}
}
Output
Below is the output I get.
class com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl
Start Element: ts
Start Element: tr
Start Element: node
End Element: node
End Element: tr
End Element: ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With