gpt4 book ai didi

java - StAX 不检索属性的数据

转载 作者:行者123 更新时间:2023-12-02 04:28:42 29 4
gpt4 key购买 nike

对于下面发布的 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
...
...

最佳答案

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

Attributes are reported as a set of events accessible from a StartElement. Other applications may report Attributes as first-order events, for example as the results of an XPath expression.

因此,您必须从 START_ELEMENT 案例中读取属性。

关于java - StAX 不检索属性的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31811987/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com