我无法读取子节点值。下面是我正在尝试阅读的XML。我想读取每个子节点的值。
<vir-analysis version="2.9">
<vehicle>
<registration>
<first-registration-date>16-Aug-1988</first-registration-date>
<registration-status>Active</registration-status>
<cause-of-last-registration>New</cause-of-last-registration>
<registered-overseas>No</registered-overseas>
<last-registration-date>16-Aug-1988</last-registration-date>
</registration>
<licence>
<expiry-date value="2016-02-13">13-Feb-2016</expiry-date>
<licence-type code="L">Licence</licence-type>
<issue-date value="2015-01-15">15-Jan-2015</issue-date>
</licence>
<wof>
<last-inspection-date>24-Feb-2015</last-inspection-date>
<last-inspection-result code="P">Pass</last-inspection-result>
<expiry-date value="2015-08-24">24-Aug-2015</expiry-date>
</wof>
<cof>
<is-subject-to value="false">No</is-subject-to>
<expiry-date value="2015-08-24">24-Aug-2015</expiry-date>
</cof>
</vir-analysis>我试图读取值的示例代码如下所示,我得到的是空值
代码:
if(xmlDoc.getElementsByTagName("licence").length!= 0){
document.getElementById('LICENCE_EXPIRY_DATE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[1].nodeValue;
document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].nodeValue; 发布于 2015-07-31 12:18:24
你需要这样做:
if(xmlDoc.getElementsByTagName("licence").length!= 0){
document.getElementById('LICENCE_EXPIRY_DATE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[1].childNodes[0].nodeValue; //a extra childnode is added to select the text node and display its content.
document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].childNodes[0].nodeValue;或者像这样使用textContent:
if(xmlDoc.getElementsByTagName("licence").length!= 0){
document.getElementById('LICENCE_EXPIRY_DATE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[1].textContent;
document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].textContent;元素上的nodeValue将返回null。但是,在text node上,它将返回值。由于文本被视为节点,所以需要选择另一个childnode。textContent为您提供元素中的所有文本。
不同的节点类型。节点内的文本被视为文本节点.这就是为什么元素上的nodeValue返回null。

https://stackoverflow.com/questions/31745740
复制相似问题