Main Page

Retrieving XML

As long as you include this code, you can use the
loadXML()
method in Mozilla the same way as in IE.
Retrieving XML
Remember that Microsoft’s XML DOM provides an
xml
property that allows easy access to the underly-
ing XML code. Because this property is not part of the standard, Mozilla doesn’t support it. Instead,
Mozilla has the
XMLSerializer
object, which is used for the same purpose:
var oSerializer = new XMLSerializer();
var sXml = oSerializer.serializeToString(oXmlDom, “text/xml”);
This simple code snippet creates the XML code for
oXmlDom
by using the
XMLSerializer
’s only
method:
serializeToString()
. The
serializeToString()
method accepts the node to serialize and
the content type as arguments. Once again, the content type can be
“text/xml”
or
“application/xml”
.
Using this object, it’s possible to synthesize the
xml
property for Mozilla using a little-known method
called
defineGetter()
.
The
defineGetter()
method exists only in Mozilla and is used to define a
getter function
for a property,
meaning that when the property is accessed in read mode, this function is called and the return value is
assigned to the property. For example:
var sValue = oXmlNode.nodeValue; //read mode
oXmlNode.nodeValue = “New value”; //write mode
The first line of code uses the
nodeValue
property in read mode, meaning that the interpreter is reading
the value from the property. If a getter function is defined, it is run and its value returned. The second
line of code uses
nodeValue
in write mode, meaning that a value is being assigned to it. If a
setter func-
tion
is defined (the opposite of a getter function), then it is called with
New value
as an argument. Yes,
there is also a
defineSetter()
method, but it’s unnecessary here.
This method,
defineGetter()
, is hidden by using the JavaScript standard for private properties and
methods — using double underscores before and after the name:
oObject.__defineGetter__(“propertyName”, function() { return “propertyValue”; });
As you can see,
defineGetter()
takes two arguments: the name of the property and the function to
call. Whatever you specify as the property name cannot be used as a regular property. For example, you
should never do this:
oObject.propertyName = “blue”;
oObject.__defineGetter__(“propertyName”, function() { return “propertyValue”; });
Typically getter and setter functions are defined in pairs, although you can effectively create a read-only
property by assigning just a getter. This is way to create the
xml
property.
This code will cause an error in IE, where no
Document
object exists. To prevent this,
use a browser detect around the code.
453
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 453


JavaScript EditorFree JavaScript Editor     Ajax Editor


©