从JavaScript中获取XML文件的价值 [英] get value from XML File in JavaScript
问题描述
我有一个XML文件,格式如下:
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>
我需要使用javascript来获取第二个容器中的第一个项目名称。我打算使用 xmldoc.getElementsByTagName(item)[3] .childNodes [0] .nodeValue;
但我无法知道将有多少项目第一个容器,所以我正在寻找一种方法来选择第二个容器然后选择项目的名称。
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.
推荐答案
首先,选择容器标签。如果您有2个或更多容器标记,请获取第二个容器的第一个子节点。像这样的东西(可能不准确,没有测试过):
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]
}
}
这篇关于从JavaScript中获取XML文件的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!