Finite Element Not Stax Detected

I am reading an XML file as shown below:

<ts> <tr comment="" label="tr1"> <node order="1" label="" /> </tr> </ts> 

And I expected the code below to display three e :

 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 that will not work! Any ideas on how I can solve the problem?

Note. I think this is due to self-closing tags, for example: <myTag id="1" />

+4
source share
2 answers

The code posted in your question caused the three e for me that are expected. I am using JDK 1.6 on Mac.

Demo

You can try running the following code to see which element end event is 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 result that 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 
+3
source

I work on Windows using JDK 1.7 and get the same results as Blaise Doughan :

 s s s e e e 

I don't think this is due to <node order="1" label="" /> , as the documentation states that:

NOTE : an empty element (for example, <tag/> ) will be reported with two separate events: START_ELEMENT , END_ELEMENT . This saves the parsing equivalence of the empty element to <tag></tag> . This method will be an IllegalStateException if it is called after hasNext() returns false.

Long shot: maybe some other related code could cause weird behavior?

+5
source

All Articles