首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法读取Java脚本中的XML子节点值

无法读取Java脚本中的XML子节点值
EN

Stack Overflow用户
提问于 2015-07-31 12:03:40
回答 1查看 973关注 0票数 0

我无法读取子节点值。下面是我正在尝试阅读的XML。我想读取每个子节点的值。

代码语言:javascript
运行
复制
 <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>

我试图读取值的示例代码如下所示,我得到的是空值

代码:

代码语言:javascript
运行
复制
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;  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-31 12:18:24

你需要这样做:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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上,它将返回值。由于文本被视为节点,所以需要选择另一个childnodetextContent为您提供元素中的所有文本。

不同的节点类型。节点内的文本被视为文本节点.这就是为什么元素上的nodeValue返回null

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31745740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档