04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 16: ECMA Script for XML<br />

You can also use the child() method to access an attribute by passing in the name of the attribute<br />

prefixed with @ as shown here:<br />

alert(employees.employee[0].child(“@position”));<br />

//”Software Engineer”<br />

Since any XML object property name can be used with child() , the @ character is necessary to<br />

distinguish between tag names and attribute names.<br />

It ’ s possible to access only attributes by using the attribute() method and passing in the name of the<br />

attribute. Unlike child() , there is no need to prefix the attribute name with an @ character. Here’s an<br />

example:<br />

alert(employees.employee[0].attribute(“position”));<br />

//”Software Engineer”<br />

These three ways of accessing properties are available on both XML and XMLList types. When used on an<br />

XML object, an XML object representing the attribute is returned; when used on an XMLList object, an<br />

XMLList is returned containing attribute XML objects for all elements in the list. In the previous example,<br />

for instance, employees.employee.@position will return an XMLList containing two objects — one<br />

for the position attribute on the first < employee/ > element and one for the second.<br />

To retrieve all attributes in an XML or XMLList object, you can use the attributes() method. This<br />

method returns an XMLList of objects representing all attributes. This is the same as using the @*<br />

pattern, as illustrated in this example:<br />

//both lines get all attributes<br />

var atts1 = employees.employee[0].@*;<br />

var atts2 = employees.employee[0].attributes();<br />

Changing attribute values in E4X is as simple as changing a property value. Simply assign a new value<br />

to the property like this:<br />

employees.employee[0].@position = “Author”;<br />

//change position attribute<br />

The change is then reflected internally, so when you serialize the XML object, the attribute value is<br />

updated. This same technique can be used to add new attributes, as shown in the following example:<br />

employees.employee[0].@experience = “8 years”;<br />

employees.employee[0].@manager = “Jim Smith”;<br />

//add experience attribute<br />

//add manager attribute<br />

Since attributes act like any other ECMAScript properties, you can also remove attributes by using the<br />

delete operator as follows:<br />

delete employees.employee[0].@position;<br />

//delete position attribute<br />

Property access for attributes allows for very simple interaction with the underlying XML structure.<br />

554

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!