Main Page

new XML

var oXml = new XML(“<person><name>Nicholas C. Zakas</name></person>”);
The second way is to use the syntax extension mentioned earlier, allowing you to enter the XML directly
into the code without using strings:
var oXml = <person>
<name>Nicholas C. Zakas</name>
</person>;
The XML is interpreted according to several flags on the
XML
constructor:
?
XML.ignoreComments
— If set to
true
, causes the parser to ignore comments
?
XML.ignoreProcessingInstructions
— If set to true, causes the parser to ignore processing
instruction.
?
XML.ignoreWhitespace
— If set to true, causes the parser to ignore whitespace between
elements
The
toString()
method is accompanied by the
toXMLString()
method, both of which returns string
representations of the XML. The
toString()
method returns an XML-encoded string if the element
contains complex children (that is, anything other than text); if the element contains only simple content
(text), then
toString()
just returns the text without the start and end tags. On the other hand,
toXMLString()
always returns the XML tags regardless of the element’s children. For example:
var oXml = <name>Nicholas C. Zakas</name>;
alert(oXml.toString()); //outputs “Nicholas C. Zakas”
alert(oXml.toXMLString()); //outputs “<name>Nicholas C. Zakas</name>”;
In the previous code, the first alert displays just
“Nicholas C. Zakas”
because the
toString()
method is called. The second alert displays the full XML code,
“<name>Nicholas C. Zakas</name>”
.
If, however, the element has complex content, both methods return the same value:
var oXml = <name><first>Nicholas</first><last>Zakas</last></name>;
alert(oXml.toString()); //outputs
“<name><first>Nicholas</first><last>Zakas</last></name>”
alert(oXml.toXMLString()); //outputs
“<name><first>Nicholas</first><last>Zakas</last></name>;”;
In this code,
toString()
and
toXMLString()
return
“<name><first>Nicholas</first><last>Zakas</last></name>”
.
Both methods use a variety of settings on the XML constructor to determine how to output the XML code:
?
XML.prettyPrinting
— When set to
true
, the methods normalize whitespace between
elements.
?
XML.prettyIndent
— Specifies the line indent in the methods. By default this is set to
2
.
All the constructor flags are stored in an object that can be referenced by using the
XML.settings()
method. This object can then be used to restore the settings later by using the
XML.setSettings()
method, as shown in this example:
609
The Evolution of JavaScript
23_579088 ch20.qxd 3/28/05 11:44 AM Page 609


JavaScript EditorFree JavaScript Editor     Ajax Editor


©