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 Answer 1

1

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]
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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!
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.