2011-06-22 41 views
0

,我有以下格式的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爲空,那麼我希望它的節點值爲空字符串""

回答

3

您必須檢查樹的每個屬性上的「undefined」。如:

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

如果您嘗試訪問的JavaScript爲空或未定義的屬性,該腳本將在該行失敗,之後不執行任何線。

要解決失敗,你可以用,可能在try{}catch(e){}

+0

這也是值得的檢查空塊是否在同一個塊中: if(typeof(element)==「undefined」|| element!= null){//用這個值做某事} 不檢查null也可能導致你的代碼崩潰。 – rav

2

我認爲你應該檢查有多少的childNodes確實筆者有失敗的那些代碼塊:

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