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

so it inherits all of the default properties and methods of all objects. There are a few ways to create a new<br />

XML object, the first of which is to call the constructor like this:<br />

var x = new XML();<br />

This line creates an empty XML object that can be filled with data. You can also pass in an XML string to<br />

the constructor as shown in this example:<br />

var x = new XML(“ < employee position=\”Software Engineer\” > < name > Nicholas “ +<br />

“Zakas < /name > < /employee > ”);<br />

The XML string passed into the constructor is parsed into an object hierarchy of XML objects.<br />

Additionally, you can pass in a DOM document or node to the constructor as follows and have its data<br />

represented in E4X:<br />

var x = new XML(xmldom);<br />

Even though these methods of construction are useful, the most powerful and interesting method is<br />

direct assignment of XML data into a variable via an XML literal. XML literals are nothing more than<br />

XML code embedded into JavaScript code. Here ’ s an example:<br />

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

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

< /employee > ;<br />

Here, an XML data structure is assigned directly to a variable. This augmented syntax creates an XML<br />

object and assigns it to the employee variable.<br />

The Firefox implementation of E4X doesn ’ t support the parsing of XML prologs. If<br />

< ?xml version= “ 1.0 ” ? > is present, either in text that is passed to the XML<br />

constructor or as part of the XML literal, a syntax error occurs.<br />

The toXMLString() method returns an XML string representing the object and its children. The<br />

toString() method, on the other hand, behaves differently based on the contents of the XML object. If<br />

the contents are simple (plain text), then the text is returned; otherwise toString() acts the same as<br />

toXMLString() . Consider the following example:<br />

var data = < name > Nicholas C. Zakas < /name > ;<br />

alert(data.toString()); //” > Nicholas C. Zakas”<br />

alert(data.toXMLString()); //” < name > Nicholas C. Zakas < /name > ”<br />

Between these two methods, most XML serialization needs can be met.<br />

548

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

Saved successfully!

Ooh no, something went wrong!