tags:

views:

97

answers:

1

I have an XML File with the following format:

<containers>
    <container>
        <item>
            item name
        </item>
        <item>
            item name
        </item>
        <item>
            item name
        </item>
    </container>
    <container>
        <item>
            item name
        </item>
    </container>
</containers>

I need to use javascript to get the first item name in the second container. I was going to use xmldoc.getElementsByTagName("item")[3].childNodes[0].nodeValue; but I have no way of knowing how many items will be in the first container, so I'm looking for a way to select the second container then the item's name.

+1  A: 

First, select the container tags. If you have 2 or more container tags, take the first child node of the second container. Something like this (may not be exact, haven't tested it):

var containers = xmldoc.getElementsByTagName("container");
if (containers.length >= 2)
{
  var items = containers[1].getElementsByTagName("item");
  if (items.length > 0)
  {
     //your item is items[0]
  }
}
wsanville
I think that's just what I was looking for to get me back on track. Had a mental block and haven't been able to get past it until now.Thanks!
Hintswen
No prob, glad to help.
wsanville
Is there a way to distinguish between a container in a container? eg. if that first container has a container inside it, that have the index of 1...
Hintswen