Search code examples
javaxmlxerces

How to get Sibling Elements when siblings have same name but different attributes using Java and Xerces NodeIterator


I am working with Java and trying to parse XML documents. I have a document which has two sibling tags having same element names as seen here:

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

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

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

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

I am using Xerces to parse the XML and NodeIterator to process it. I want to get the second element <application> whose attribute id="ID2" from the sample XML above. When using the method getElementsByTagName("tagname"), the element being returned is always the first element whose attribute id="ID1".

How do I get the second element which has the same name and similar attributes, though different values for the attributes?


Solution

  • getElementsByTagName("application") returns a NodeList. To get the second element, you can use

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

    If you want to be sure, you need to iterate over the applications until you find a node with the 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 ...
        }
    }
    

    Note: If you can, try to switch to JDOM2. It has a much nicer API, especially when you use Java 6 or better.