gpt4 book ai didi

javascript - 使用javascript从XML字符串中获取节点值

转载 作者:行者123 更新时间:2023-11-30 10:08:58 26 4
gpt4 key购买 nike

我正在尝试从 XML 字符串中检索“代码”和“值”。

我有以下 XML 字符串:

<items>
<item>
<id>55</id>
<attributes>
<attribute>
<code>ID</code>
<value><![CDATA[55]]></value>
</attribute>
<attribute>
<code>Chip_ID</code>
<value><![CDATA[1]]></value>
</attribute>
<attribute>
<code>FilterKey</code>
<value><![CDATA[5]]></value>
</attribute>
<attribute>
<code>DateTime</code>
<value><![CDATA[22/12/2014 12:21:25]]></value>
</attribute>
</attributes>
</item>
</items>

然后我有以下 javaScript 来识别每个节点:

var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
xmlDocument.async = false;
xmlDocument.loadXML(pXML);

var oFirstNode = xmlDocument.documentElement;

var item = oFirstNode.childNodes[0]; //10 of these and they represent the items
//alert("1 "+item.nodeName);

var ID = item.childNodes[0]; //one of these for each level-ID - NO CHILDREN
var attributes = item.childNodes[1]; //one of these for each level-attributes
//alert("2 " + ID.nodeName);
//alert("2 " + attributes.nodeName);

var attribute = attributes.childNodes[0];//4 of these for each level and they all have 2 children-code and value
//alert("3 " + attribute.nodeName);

var code = attribute.childNodes[0];
var value = attribute.childNodes[1];

alert(code.nodeName);
alert(value.nodeName);

我知道我在正确的节点,因为警报框都给出了预期值。

我现在想检索“code”和“value”的文本,例如第一个条目应该返回 code = ID值 = ![CDATA[55]]

我试过:

alert(code.nodeValue);
alert(value.nodeValue);

但它们都返回 null。

最佳答案

DOM 元素的 .nodeValue 属性是 always null .

使用.textContent相反。

alert(code.textContent);


我还建议使用不需要按索引筛选每个子节点的 DOM 遍历方法:

var attributes = item.getElementsByTagName("attribute"); // should contain 4 elements

另请参阅:nodeValue vs innerHTML and textContent. How to choose?

关于javascript - 使用javascript从XML字符串中获取节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com