我正在读取与以下相同的XML文件:

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

我希望下面的代码在屏幕上打印出三个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");
    }
}

但这是行不通的!关于如何解决此问题的任何想法?

注意:我认为它与自封闭标签有关,例如:<myTag id="1" />

最佳答案

您的问题中张贴的代码为我生成了三个e,这是预期的。我在Mac上使用的是JDK 1.6。

演示

您可能想尝试运行以下代码,以查看缺少的结束元素事件:

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());
            }
        }
    }

}

输出

以下是我得到的输出。
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

10-06 14:09