【问题标题】:Handle Empty #text in XML DOM处理 XML DOM 中的空 #text
【发布时间】: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&lt;item&gt; 标记的DOM 元素。作者为非空时代码运行正常,但author为空时代码不运行。我该如何解决这个问题?如果author 为空,那么我希望它的节点值为空字符串""

【问题讨论】:

    标签: javascript xml parsing dom


    【解决方案1】:

    我觉得你应该看看作者有多少个子节点:

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

    【讨论】:

      【解决方案2】:

      您必须在树的每个属性上检查“未定义”。如:

      if( typeof (element) == "undefined" ){ //set var to empty string }

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

      为了避免失败,您可以将那些可能失败的代码块包装在try{}catch(e){}

      【讨论】:

      • 在同一块中检查 null 也是值得的: if( typeof (element) == "undefined" || element != null ){ //do something with this value } 不检查for null 也会让你的代码出错。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多