Alex Rivera | Logout

JAVA element.getElementsByTagName Restrict to Top Level

Asked 2009-08-06T21:15:58.057
21

I have an XML file as follows:

<rootNode>
    <link>http://rootlink/</link>
    <image>
        <link>http://imagelink/</link>
        <title>This is the title</title>
    </image>
</rootNode>

The XML Java code using DOM is as follows:

NodeList rootNodeList = element.getElementsByTagName("link");

This will give me all of the "link" elements including the top level and the one inside the "image" node.

Is there a way to just get the "link" tags for rootNode within one level and not two such as is the case for the image link? That is, I just want the http://rootlink/ "link".

Edit
Report

1 Answer

11

I couldn't find any methods to do that either so I wrote this helper function,

 public static List<Element> getChildrenByTagName(Element parent, String name) {
    List<Element> nodeList = new ArrayList<Element>();
    for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child.getNodeType() == Node.ELEMENT_NODE && 
          name.equals(child.getNodeName())) {
        nodeList.add((Element) child);
      }
    }

    return nodeList;
  }
answered 2009-08-07T00:12:59.937

Your Answer