Entry
How can I access the attributes of an XML object representing an element?
How can I access the attributes of an XML object representing an element?
Apr 4th, 2005 03:38
Martin Honnen,
Attributes of an XML object representing an element are accessed like
properties besides that the attribute name is prefixed with the
character '@' e.g. using the dot notation
xmlObject.@attributeName
or using the bracket notation
xmlObject['@attributeName']
Thus if you have the following XML object
var xmlObject = <god name="Kibo" power="42" />;
then you can access the attributes using the dot notation as
alert(xmlObject.@name); // shows 'Kibo'
alert(xmlObject.@power); // shows 42
or using the bracket notation as
alert(xmlObject['@name']); // shows 'Kibo'
alert(xmlObject['@power']); // shows 42
As with normal properties the dot notation is used when the attribute
name is known while writing the script and as long as it follows the
constraints on identifiers while the bracket notation is used when the
attribute name is not an identifier or has to be established from a
JavaScript expression at run time.
For instance while XML allows attribute names with a '-' character as in
var xmlObject = <book published-at="2005-04-02" />;
the JavaScript expression
alert(xmlObject.@published-at);
will give an error that 'at' is not defined so to access an attribute
with that kind of name you need to use the bracket notation as in
alert(xmlObject['@published-at']);
As with child node access of XML nodes where the character '*' can be
used as a wild card to access all child nodes for attribute access you
can use the special attribute identifier '@*' as a wild card to access
all attributes:
var xmlObject = <god name="Kibo" power="42" />;
var attributeList = xmlObject.@*;
alert(attributeList.length()); // shows 2
If you are scripting XML with namespaces then you need to be aware that
the wild card '@*' shown above selects all attributes with no namespace,
if you are also looking for attributes in a namespace then you need the
qualified identifier '@*::*', see
http://www.faqts.com/knowledge_base/view.phtml/aid/35171 for details on
how to access attributes in a namespace with qualified identifiers.
Contrary to normal objects and normal properties where trying to access
a non existing property (e.g. object.propertyName or
object['propertyName']) yields the value undefined with an XML object
the attempt to acccess a not existing attribute yields an empty XMLList
object:
var xmlObject = <god name="Kibo" power="42" />;
var whatIsThis = xmlObject.@home;
alert(whatIsThis.length()); // shows 0