我有一个以下格式的 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/