Fortisimo
Fortisimo

Reputation: 1002

XML parse sub-parents of root node

Here's books.xml, an xml that I'm trying to traverse:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<bookstore>
<book category="cooking">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <year>2005</year>
 <price>30.00</price>
</book>
<book category="children">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <year>2005</year>
 <price>29.99</price>
</book>
<book category="web">
 <title lang="en">XQuery Kick Start</title>
 <author>James McGovern</author>
 <author>Per Bothner</author>
 <author>Kurt Cagle</author>
 <author>James Linn</author>
 <author>Vaidyanathan Nagarajan</author>
 <year>2003</year>
 <price>49.99</price>
</book>
<book category="web" cover="paperback">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <year>2003</year>
 <price>39.95</price>
</book>
</bookstore>

I want to go to each book and extract all of its children's data, however, I'm having probems: It keeps returning null instead of the values of the text nodes. Here's my code:

<html>
<head>
<script type="text/javascript" src="loadXML.js">
</script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
var x = xmlDoc.getElementsByTagName("book");
for(var i=0;i<x.length;i++)
{
    var y = x[i].childNodes;
    for(var j=0;j<y.length;j++)
    {
        document.write(y[j].nodeValue);
        document.write("<br>");
    }
    document.write("<br>");
}
</script>

</body>
</html>

Upvotes: 0

Views: 564

Answers (1)

John Kugelman
John Kugelman

Reputation: 362087

Text data is stored in text nodes, not in the element nodes. Try something like this:

if (y[j].firstChild != null) {
    document.write(y[j].firstChild.nodeValue);
}

The childNodes[0] will get the first child node of each <title>, <author>, <year>, etc., element, which in each case will be a text node containing the text of the element. That text node will then have a usable nodeValue.

The if is necessary to weed out the child nodes of your <book> elements which aren't elements. There are actually hidden text nodes in there containing spaces and newlines which you need to ignore.

Upvotes: 1

Related Questions