Javascript xml文档并查找

时间:2015-08-11 18:57:40

标签: javascript xml

假设我有以下非常简单的XML片段:

<assignmentOptions>
    <MessageCharacterLimit value="4000" type="integer"></MessageCharacterLimit>
</assignmentOptions>
<options>
    <MessageCharacterLimit value1="1000" type="integer"></MessageCharacterLimit>
    <MessageCharacterLimit value2="2000" type="integer"></MessageCharacterLimit>
</options>

如何找到<options>下的所有MessageCharacterLimit? MessageCharacterLimit不是唯一的,但选项/ MessageCharacterLimit是。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用querySelectorAll()

var a = document.querySelectorAll('options > MessageCharacterLimit');
console.log(a)
<assignmentOptions>
    <MessageCharacterLimit value="4000" type="integer"></MessageCharacterLimit>
</assignmentOptions>
<options>
    <MessageCharacterLimit value1="1000" type="integer"></MessageCharacterLimit>
    <MessageCharacterLimit value2="2000" type="integer"></MessageCharacterLimit>
</options>

然后你可以循环遍历这样的集合:

var a = document.querySelectorAll('options > MessageCharacterLimit');
for (var i = 0; i<a.length; i++) {
    console.log(a[i].getAttribute('type'));
}
<assignmentOptions>
    <MessageCharacterLimit value="4000" type="integer"></MessageCharacterLimit>
</assignmentOptions>
<options>
    <MessageCharacterLimit value1="1000" type="integer"></MessageCharacterLimit>
    <MessageCharacterLimit value2="2000" type="integer"></MessageCharacterLimit>
</options>