0

I have following XML structure

<urlset><!--  lib.meine_sitemap [begin] -->
    <menu level="1">
         <title>Products</title>
         <url>index.php?id=395</url>
         <menu level="2">
              <title>Title</title>
              <url>index.php?id=426</url>
              <menu level="3">
                  <title>Title</title>         
                  <url>index.php?id=437</url>
                  <cat>41</cat>
                  <cat>42</cat>
              </menu>
              <menu level="3">
                  <title>Title</title>                        
                  <url>index.php?id=436</url>
                  <cat>80</cat>
              </menu> 
         </menu> 
    </menu>
(...)
</urlset>

Now I want to get all child nodes of "menu level 1". To display the title in a list view. When I am using:

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));
Document doc = dBuilder.parse(is);
NodeList nodes = doc.getElementsByTagName("menu");

I get ALL Elements and not only the child nodes of menu level 1.

When I am using

NodeList nodes = doc.getChildElements();

This seems to work, but then I cant do this again:

nodes.item(0).getChildElements();

How can I achieve that I only get the child menus of a node?

Thanks!

johnbraum
  • 276
  • 4
  • 18
  • Propably related: http://stackoverflow.com/questions/10689900/get-xml-only-immediate-children-elements-by-name – Capricorn Aug 26 '15 at 09:23

1 Answers1

0

So finally I got a solution. The trick ist to use node.getNextSibling()

The following code gets all menu Tags and then read the title Tag of them and add it to an Arraylist.

private void diveDeep(int index)
{
    currentNode = (Node)currentNodes.get(index);

    currentNodes = new ArrayList<Node>();
    valueList = new ArrayList<String>();

    Node childNode = currentNode.getFirstChild();

    while(childNode.getNextSibling() != null)
    {
        childNode = childNode.getNextSibling();
        if(childNode.getNodeName().equals("menu"))
        {
            currentNodes.add(childNode);
            NodeList nodes = childNode.getChildNodes();

            for(int i = 0; i < nodes.getLength(); i++)
            {
                if(nodes.item(i).getNodeName().equals("title"))
                {
                    valueList.add(nodes.item(i).getTextContent());
                }
            }
        }
    }
}
johnbraum
  • 276
  • 4
  • 18