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 />

The child() method behaves in the exact same way as property access. Any property name or index<br />

can be passed into the child() method and it will return the same value. Consider this example:<br />

var firstChild = employees.child(0);<br />

//same as employees.*[0]<br />

var employeeList = employees.child(“employee”); //same as employees.employee<br />

var allChildren = employees.child(“*”);<br />

//same as employees.*<br />

For added convenience, a children() method is provided that always returns all child elements. Here’s<br />

an example:<br />

var allChildren = employees.children(); //same as employees.*<br />

There is also an elements() method, which behaves similar to child() with the exception that it will<br />

return only XML objects that represent elements. For example:<br />

var employeeList = employees.elements(“employee”); //same as employees.employee<br />

var allChildren = employees.elements(“*”);<br />

//same as employees.*<br />

These methods provide a more familiar syntax for JavaScript developers to access XML data.<br />

Child elements can be removed by using the delete operator as shown here:<br />

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

alert(employees.employee.length()); //1<br />

This is one of the major advantages of treating child nodes as properties.<br />

Accessing Attributes<br />

Attributes can also be accessed using dot notation, although the syntax is slightly augmented. To<br />

differentiate an attribute name from a child - element tag name, you must prepend an “ at ” character (@)<br />

before the name. This syntax is borrowed from XPath, which also uses @ to differentiate between<br />

attributes and character names. The result is a syntax that looks a little strange, as you can see in this<br />

example:<br />

var employees = < employees ><br />

< employee position=”Software Engineer” ><br />

< name > Nicholas C. Zakas < /name ><br />

< /employee ><br />

< employee position=”Salesperson” ><br />

< name > Jim Smith < /name ><br />

< /employee ><br />

< /employees > ;<br />

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

As with elements, each attribute is represented as a property that can be accessed using this shorthand<br />

notation. An XML object representing the attribute is returned and its toString() method always<br />

returns the attribute value. To get the attribute name, use the name() method of the object.<br />

553

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

Saved successfully!

Ooh no, something went wrong!