Handle Empty #text in XML DOM

I have an XML document of the following format:

<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>

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 "".

Answers


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){}


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;
}

Need Your Help

Haskell: How to test a (reactive) FSM with quickcheck?

testing haskell quickcheck frp

I wrote a finite state machine module for a little soccer game I'm currently working at. It provides an interface for setting up an FSM (basically its states and transitions). For each state, you can

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.