Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End element isn't detected by Stax

Tags:

java

xml

stax

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" />

like image 396
masoud Avatar asked Aug 25 '12 17:08

masoud


2 Answers

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 an IllegalStateException if it is called after hasNext() returns false.

Long shot: maybe some other related code may be causing the weird behavior?

like image 115
juan.facorro Avatar answered Nov 17 '22 19:11

juan.facorro


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
like image 3
bdoughan Avatar answered Nov 17 '22 19:11

bdoughan