【问题标题】:How to get Sibling Elements when siblings have same name but different attributes using Java and Xerces NodeIterator如何使用 Java 和 Xerces NodeIterator 在兄弟姐妹名称相同但属性不同时获取兄弟姐妹元素
【发布时间】:2015-05-22 14:16:21
【问题描述】:

我正在使用 Java 并尝试解析 XML 文档。我有一个文档,其中包含两个具有相同元素名称的兄弟标签,如下所示:

<directory>
    ... <!-- other data and elements -->

    <application id="ID1">
    </application>

    ... <!-- other elements -->

    <application id="ID2">
    </application>
    ... <!-- other element and data -->
</directory>

我正在使用 Xerces 来解析 XML,并使用 NodeIterator 来处理它。我想从上面的示例 XML 中获取第二个元素 &lt;application&gt;,其属性为 id="ID2"。使用getElementsByTagName("tagname")方法时,返回的元素总是第一个属性为id="ID1"的元素。

如何获得具有相同名称和相似属性的第二个元素,但属性值不同?

【问题讨论】:

    标签: java xml xerces


    【解决方案1】:

    getElementsByTagName("application") 返回一个NodeList。要获取第二个元素,您可以使用

    NodeList applications = getElementsByTagName("application");
    Node second = applications.item(1);
    

    如果你想确定,你需要遍历applications,直到找到一个带有id == "ID2"的节点:

    for( int i=0; i<applications.length(); i++) {
        Node node = applications.item(i);
        if(!(node instanceof Element)) continue;
        Element e = (Element) node;
        String id = e.getAttributeNode("id").getValue();
        if("ID2".equals(id)) {
            ... do something with the node ...
        }
    }
    

    注意:如果可以,请尝试切换到JDOM2。它具有更好的 API,尤其是当您使用 Java 6 或更高版本时。

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      相关资源
      最近更新 更多