How to check if an element exist reading XML...

N

neousr

<record>
<title>Lunar Park</title>
<author>Bret Easton Ellis</author>
<publisher></publisher>
<year>2005</year>
</record>

xAuthor =
x.getElementsByTagName("author")[0].firstChild.nodeValue
xPublisher =
x.getElementsByTagName("publisher")[0].firstChild.nodeValue

I'm retrieving data from a xml file, and I need to display that data in
a table, but as soon as I try to reference an element that it's empty
the browser stops working...

Is there any way to prevent this (so, to know wich elements are empty
in a certain "record")?

Thanks a lot in advance.
 
R

RobG

<record>
<title>Lunar Park</title>
<author>Bret Easton Ellis</author>
<publisher></publisher>
<year>2005</year>
</record>

xAuthor =
x.getElementsByTagName("author")[0].firstChild.nodeValue
xPublisher =
x.getElementsByTagName("publisher")[0].firstChild.nodeValue

I'm retrieving data from a xml file, and I need to display that data in
a table, but as soon as I try to reference an element that it's empty
the browser stops working...


Yes, because if there is no firstChild, attempting to get its nodeValue
will cause an error. You could try:

var t = x.getElementsByTagName("author");
xAuthor = (t[0] && t[0].firstChild)? t[0].firstChild.nodeValue : '';

Is there any way to prevent this (so, to know wich elements are empty
in a certain "record")?

A more robust solution is to write a getValue() function:

xAuthor = getValue(x.getElementsByTagName("author"));


and getValue() can be something like:

function getValue(C){
var val='';
for (var i=0, len=C.length; i<len; ++i){
val += C.nodeValue;
}
return val;
}

You may want to add some smarts to getValue() to manage different
element types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,269
Messages
2,571,098
Members
48,773
Latest member
Kaybee

Latest Threads

Top