tags:

views:

1772

answers:

3

I have an XML file as follows:

<rootNode>
    <link>http://rootlink/&lt;/link&gt;
    <image>
        <link>http://imagelink/&lt;/link&gt;
        <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".

+1  A: 

If you can use JDOM instead, you can do this:

element.getChildren("link");

With standard Dom the closest you can get is to iterate the child nodes list (by calling getChildNodes() and checking each item(i) of the NodeList, picking out the nodes with the matching name.

Rich Seller
I thought about JDOM, but I've written a lot of code with DOM. I have to look at the level of effort to convert. But is there no way to do it with DOM?
I don't think there is a convenient way to do it. but you can create a method that gets calls getChildNodes(), checks each item's name, adds the items to a new NodeList, then returns the NodeList. Use that method wherever you need to get the named children. Or bite the bullet and use JDom, I find it a lot easier to deal with.
Rich Seller
Thank you. I will look into the different solutions suggested. Thanks for the quick response.
+2  A: 

You could use XPath:

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
NodeList links = (NodeList) xpath.evaluate("rootNode/link", element,
    XPathConstants.NODESET);
McDowell
Thanks for the quick response.
A: 

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;
  }
ZZ Coder
Sri Kumar