I have an XML document of the following format:
<root>
&开发者_StackOverflow中文版lt;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>
As you can see, all item
tags have the children type, name, author, content
, however for some cases, the author
tag might contain an empty #text
child.
In a Javascript file, I have the following code to get the text values of these tags from the item
DOM element:
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;
The variable item
is the DOM element for the <item>
tag. The code runs fine when the author is non-empty, but when author
is empty, the code does not run. How do I solve this? If author
is empty, then I want its node value to be the empty string ""
.
I think you should check how many childNodes does the author have:
if (item.getElementsByTagName("author")[0].childNodes.length == 0) {
this.author = '';
} else {
this.author = item.getElementsByTagName("author")[0].childNodes[0].nodeValue;
}
You have to check for "undefined" on each property of the tree. As in:
if( typeof (element) == "undefined" ){
//set var to empty string
}
If you try to access a property of a javascript that is null or undefined, the script will fail at that line and not execute any lines after it.
To get around failing, you can wrap those blocks of code that may fail in a try{}catch(e){}
精彩评论