开发者

get value from XML File in JavaScript

开发者 https://www.devze.com 2022-12-19 21:07 出处:网络
I have an XML File with the following format: <containers> <container> <item> item name

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 m开发者_如何学JAVAany items will be in the first container, so I'm looking for a way to select the second container then the item's name.


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]
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消