[英]Getting node value from XML string using javascript
我正在嘗試從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);
我知道我在正確的節點上,因為警報框都給出了期望值。
我現在想檢索“代碼”和“值”的文本,例如,第一個條目應返回代碼= ID值=![CDATA [55]]
我努力了:
alert(code.nodeValue);
alert(value.nodeValue);
但它們都返回null。
DOM元素的.nodeValue
屬性始終為null 。
請改用.textContent
。
alert(code.textContent);
我還建議使用不需要遍歷索引的DOM遍歷方法:
var attributes = item.getElementsByTagName("attribute"); // should contain 4 elements
我找到了答案。 由於某種原因,它將標簽內的值視為元素的子級,因此nodeValue返回我想要的值。 以下是我的工作解決方案:
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
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(attributes.childNodes.length);
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.childNodes[0].nodeValue)
alert(value.childNodes[0].nodeValue)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.