
CHAPTER 9: Integrating XML into JavaScript The XML Object 238
If an element is empty in the XML, the corresponding property exists and contains an empty XML object; it
is never
null or undefined.
Accessing XML elements
This sample XML code is used for examples throughout this chapter:
<bookstore>
<book category="COOKING">
<title lang="en">The Boston Cooking-School Cookbook</title>
<author>Fannie Merrit Farmer</author>
<year>1896</year>
<price>49.99</price>
</book>
<book category="CHILDREN">
<title lang="en">The Wonderful Wizard of Oz</title>
<author>L. Frank Baum</author>
<year>1900</year>
<price>39.95</price>
</book>
<book category="CHILDREN">
<title lang="en">Alice’s Adventures in Wonderland</title>
<author>Charles "Lewis Carroll" Dodgeson</author>
<author>Charles Dodgeson</author>
<author>Lewis Carroll</author>
<year>1865</year>
<price>29.99</price>
</book>
<book category="MUSIC">
<title lang="en">Gilbert and Sullivan Opera; A History and a Comment</title>
<author>H. M. Walbrook</author>
<year>1922</year>
<price>30.00</price>
</book>
</bookstore>
To encapsulate this code in an XML object, serialize it into a string and pass that string to the constructor:
var bookXmlStr = "...";
var bookstoreXML = new XML (bookXmlStr);
Using this example, the root element <bookstore>, is represented by the XML object returned from the
constructor. Each of the
<book> elements is available as a member of the book property of the XML object.
X The Javascript statement bookstoreXML.book; returns the entire list of books.
X The statement bookstoreXML.book[0]; returns the XML object for the first book.
X The statement bookstoreXML.book[0].author; returns all authors of the first book.
For additional ways of accessing elements in the tree, see “
Retrieving contained elements” on page 241,
and “
Creating and accessing namespaces” on page 242.
Comentários a estes Manuais