
CHAPTER 9: Integrating XML into JavaScript The XML Object 243
<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>
<kids:book category="CHILDREN">
<title lang="en">The Wonderful Wizard of Oz</title>
<author>L. Frank Baum</author>
<year>1900</year>
<price>39.95</price>
</kids:book>
...
When this namespace is defined, the simple statement bookstoreXML.book no longer returns "The
Wonderful Wizard of Oz", because that book is no longer in the default namespace. To access that book,
you must define a Namespace object
for the namespace, and use it to access the element.
For example, this JavaScript code creates a Namespace object
for the namespace defined in the
<bookstore> element, and accesses the books in the namespace through that object:
var ns = new Namespace ("http://kids.mybookstore.com");
bookstoreXML.ns::book;
Setting a default namespace
By default, the default namespace is a namespace whose URI is the empty string. It is possible to set the
default namespace; in this case, simple accessors access elements that are in that namespace.
To set the default namespace, use the global function setDefaultXMLNamespace()
, or this syntax:
default xml namespace = namespace_specifier;
The namespace specifier can be either a Namespace object, or a URL string. For example:
default xml namespace = "http://books.mybookstore.com";
Once you have set the default namespace:
X Elements that are meant to be in the default namespace (and thus accessible with simple accessors)
must use the namespace prefix.
X All elements that do not have a specific namespace assignment are in the empty namespace, rather
than the default namespace. In order to access them, you must use a Namespace object
with the
empty string as the URI.
Accessing elements in namespaces
X You can access elements that are in the default namespace directly, without using a Namespace
object.
Z If you have not set a default, you can use direct access for elements with no namespace specifier.
Z If you have set a default, you can use direct access for elements in that namespace.
Comentarios a estos manuales