,我有以下格式的XML文檔:在處理XML DOM空#text
<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
爲空,那麼我希望它的節點值爲空字符串""
。
這也是值得的檢查空塊是否在同一個塊中: if(typeof(element)==「undefined」|| element!= null){//用這個值做某事} 不檢查null也可能導致你的代碼崩潰。 – rav