gpt4 book ai didi

javascript - 处理 XML DOM 中的空 #text

转载 作者:行者123 更新时间:2023-11-28 13:59:07 24 4
gpt4 key购买 nike

我有一个以下格式的 XML 文档:

<root>
<item>
<type>link</type>
<name>Nyan Cat!</name>
<author></author>
<content>http://nyan.cat/</content>
</item>

<item>
<type>quote</type>
<name>Belief and Intelligence</name>
<author>Robert Anton Wilson</author>
<content>Belief is the death of intelligence.</content>
</item>
</root>

如您所见,所有 item标签有 child type, name, author, content ,但是对于某些情况,author标签可能包含空 #text child 。

在 Javascript 文件中,我有以下代码来从 item 获取这些标签的文本值。 DOM 元素:

this.type = item.getElementsByTagName("type")[0].childNodes[0].nodeValue;
this.name = item.getElementsByTagName("name")[0].childNodes[0].nodeValue;
this.author = item.getElementsByTagName("author")[0].childNodes[0].nodeValue;
this.content = item.getElementsByTagName("content")[0].childNodes[0].nodeValue;

变量item<item> 的 DOM 元素标签。当作者非空时,代码运行良好,但当 author 时,代码运行良好。为空,代码不运行。我该如何解决这个问题?如果author为空,那么我希望它的节点值为空字符串 "" .

最佳答案

我认为你应该检查作者有多少个childNode:

if (item.getElementsByTagName("author")[0].childNodes.length == 0) {
this.author = '';
} else {
this.author = item.getElementsByTagName("author")[0].childNodes[0].nodeValue;
}

关于javascript - 处理 XML DOM 中的空 #text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6446440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com