StAX不检索属性的数据

时间:2015-08-04 14:26:24

标签: java xml dom sax stax

对于belwo发布的xml文件,我正在使用StAX来处理它。我使用下面的代码,但我不知道为什么没有关于属性的信息打印,尽管xml文件中有属性。 我希望控制台显示有关“id”,“lat”和“lon”属性的信息

男女混合

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {

        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            Log.d(TAG, "main", "@START_ELEMENT");
            Log.d(TAG, "main", "getLocalName(): "+parser.getLocalName());
            Log.d(TAG, "main", "getAttributeCount(): "+parser.getAttributeCount());
            break;

        case XMLStreamConstants.CHARACTERS:
            //Log.d(TAG, "main", "@CHARACTERS");
            //Log.d(TAG, "main", "getTextLength(): "+parser.getTextLength());
            break;

        case XMLStreamConstants.ATTRIBUTE:
            Log.d(TAG, "main", "@ATTRIBUTE");
            Log.d(TAG, "main", "getText():"+parser.getText());
            Log.d(TAG, "main", "getAttributeCount(): "+parser.getAttributeCount());
            Log.d(TAG, "main", "getAttributeCount(): "+parser.getAttributeLocalName(0));
            break;

        case XMLStreamConstants.END_ELEMENT:
            Log.d(TAG, "main", "@END_ELEMENT");
            Log.d(TAG, "main", "getText():"+parser.getLocalName());
            break;
        }

    }

XML

<?xml version='1.0' encoding='utf-8' ?>
<osm>
<node id="25779111" lat="53.0334062" lon="8.8461545"/>
<node id="25779112" lat="53.0338904" lon="8.846314"/>
<node id="25779119" lat="53.0337395" lon="8.8489255"/>
<tag k="maxspeed" v="30"/>
<tag k="maxspeed:zone" v="yes"/>
<ele k="maxspeed:zone" v="60"/>
<node id="25779114" lat="53.334062" lon="8.841545"/>
<node id="25779117" lat="53.338904" lon="8.84614"/>
<node id="25779110" lat="53.33795" lon="8.489255"/>
<tag k="maxspeed" v="32"/>
<tag k="maxspeed:zone" v="no"/>
</osm>

输出

1: D: MainClass -> main: @START_ELEMENT
2: D: MainClass -> main: getLocalName(): osm
3: D: MainClass -> main: getAttributeCount(): 0
4: D: MainClass -> main: @START_ELEMENT
5: D: MainClass -> main: getLocalName(): node
6: D: MainClass -> main: getAttributeCount(): 3
7: D: MainClass -> main: @END_ELEMENT
8: D: MainClass -> main: getText():node
9: D: MainClass -> main: @START_ELEMENT
10: D: MainClass -> main: getLocalName(): node
11: D: MainClass -> main: getAttributeCount(): 3
12: D: MainClass -> main: @END_ELEMENT
13: D: MainClass -> main: getText():node
14: D: MainClass -> main: @START_ELEMENT
15: D: MainClass -> main: getLocalName(): node
16: D: MainClass -> main: getAttributeCount(): 3
17: D: MainClass -> main: @END_ELEMENT
18: D: MainClass -> main: getText():node
...
...

1 个答案:

答案 0 :(得分:2)

这很正常:查看javax.xml.stream.events.Attributes的javadoc:

  

属性报告为可从StartElement访问的一组事件。其他应用程序可以将属性报告为一阶事件,例如作为XPath表达式的结果。

因此,您必须阅读START_ELEMENT案例中的属性。