Main Page

XML

In the
XMLList
object, methods generally call the method of the same name on each
XML
object in the
list and return the results in another
XMLList
object. For example, if you call
attribute(“id”)
on an
XMLList
object, it calls the
attribute(“id”)
on each
XML
object. If the
XML
object returns an attribute,
that attribute is added to the result
XMLList
object. Once all
XML
objects have contributed, the result
XMLList
object is returned. Here’s a list of all the methods that act this way:
?
attribute()
— Returns an
XMLList
of the given attribute from all
XML
objects
?
attributes()
— Returns an
XMLList
of all attributes from all
XML
objects
?
child()
— Returns an
XMLList
of all child nodes with the given name from all
XML
objects
?
children()
— Returns an
XMLList
of all child nodes from all
XML
objects
?
comments()
— Returns an
XMLList
of all child comment nodes from all
XML
objects
?
descendants()
— Returns an
XMLList
of all descendant nodes from all
XML
objects
?
elements()
— Returns an
XMLList
of all child elements nodes from all
XML
objects
?
normalize()
— Normalizes each
XML
object
?
processingInstructions()
— Returns an
XMLList
of all child processing instruction nodes
from all
XML
objects
?
text()
— Returns an
XMLList
of all child text nodes from all
XML
objects
The two methods that didn’t make sense for the
XML
object,
length()
and
contains()
, make much
more sense when used in the context of an
XMLList
. The
length()
method returns the number of
objects in the
XMLList
; the
contains()
method determines if a given XML object is contained within
the
XMLList
, for example:
var oXml1 = <name>Nicholas C. Zakas</name>;
var oXml2 = <name>Michael Smith</name>;
var oXmlList = oXml1 + oXml2;
alert(oXmlList.contains(oXml1)); //outputs “true”
In this example,
oXmlList
is created by combining
oXml1
and
oXml2
, so when the
contains()
method
is called with
oXml1
, the result is
true
.
Four other methods behave somewhat differently from the
XML
object:
?
copy()
— Returns an exact duplicate of the
XMLList
object
?
hasComplexContent()
— Returns
true
when the
XMLList
contains one element with com-
plex content or when the
XMLList
contains more than one
XML
object
?
hasSimpleContent()
— Returns
true
when the
XMLList
is empty and when the
XMLList
contains one
XML
object with simple content
?
parent()
— Returns an
XML
object if all objects in the
XMLList
have the same parent; other-
wise returns
undefined
Together, the
XML
and
XMLList
classes provide a very powerful interface to manipulate XML data.
615
The Evolution of JavaScript
23_579088 ch20.qxd 3/28/05 11:44 AM Page 615


JavaScript EditorFree JavaScript Editor     Ajax Editor


©