我正在尝试从 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>
Run Code Online (Sandbox Code Playgroud)
然后我有以下 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);
Run Code Online (Sandbox Code Playgroud)
我知道我在正确的节点,因为警报框都给出了预期值。
我现在想检索“代码”和“值”的文本,例如第一个条目应返回代码 = ID 值 = ![CDATA[55]]
我试过了:
alert(code.nodeValue);
alert(value.nodeValue);
Run Code Online (Sandbox Code Playgroud)
但他们都归零了。
.nodeValueDOM 元素的属性始终为 null。
使用.textContent来代替。
alert(code.textContent);
Run Code Online (Sandbox Code Playgroud)
我还建议使用不需要按索引筛选每个子节点的 DOM 遍历方法:
var attributes = item.getElementsByTagName("attribute"); // should contain 4 elements
Run Code Online (Sandbox Code Playgroud)
另请参阅:nodeValue 与 innerHTML 和 textContent。如何选择?