【发布时间】:2011-06-22 20:54:26
【问题描述】:
我有一个以下格式的 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 标记都有子type, name, author, content,但是在某些情况下,author 标记可能包含一个空的#text 子标记。
在 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 为空,那么我希望它的节点值为空字符串""。
【问题讨论】:
标签: javascript xml parsing dom