【发布时间】:2015-02-20 16:23:33
【问题描述】:
我正在尝试从 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。
【问题讨论】:
标签: javascript xml dom nodes