Javascript 处理XML DOM中的空#文本

Javascript 处理XML DOM中的空#文本,javascript,xml,parsing,dom,Javascript,Xml,Parsing,Dom,我有一个以下格式的XML文档: <root> <item> <type>link</type> <name>Nyan Cat!</name> <author></author> <content>http://nyan.cat/</content> </item> <it

我有一个以下格式的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
标记的DOM元素。当作者为非空时,代码运行正常,但当
author
为空时,代码不运行。我如何解决这个问题?如果
author
为空,则我希望其节点值为空字符串

您必须检查树的每个属性是否为“未定义”。例如:

if(元素的类型)=“未定义”){
//将var设置为空字符串
}

如果您试图访问一个为null或未定义的javascript属性,那么脚本将在该行失败,并且不会在其后执行任何行


为了避免失败,您可以在
try{}catch(e){}

中包装那些可能失败的代码块。我认为您应该检查作者有多少子节点:

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

在同一块中检查null也是值得的:如果(typeof(element)=“undefined”| | element!=null){//使用此值执行某些操作}不检查null也会使代码出错。
if (item.getElementsByTagName("author")[0].childNodes.length == 0) {
    this.author = '';
} else {
    this.author = item.getElementsByTagName("author")[0].childNodes[0].nodeValue;
}