↑
Main Page
Loading XML
This line of code creates an XML DOM that represents the XML code
<root/>
. If you specify a names-
pace URL in the first argument, you can further define the document element:
var oXmlDom = document.implementation.createDocument(“http://www.wrox.com”,
“root”, null);
This line of code creates an XML DOM representing
<a0:root xmlns:a0=”http://www.wrox.com”
/>
. Mozilla automatically creates a namespace named
a0
to represent the URL you entered for the
namespace.
Loading XML
Unlike Microsoft’s XML DOM, Mozilla’s only supports one method for loading data:
load()
. The
load()
method in Mozilla works exactly the same as the
load()
method in Internet Explorer. All you
need is to specify the XML file to load and whether to load it synchronously or asynchronously (default).
To load the XML file synchronously, the code is essentially the same as in IE:
oXmlDom.async = false;
oXmlDom.load(“test.xml”);
If you want to load a file asynchronously, things are a little bit different.
Mozilla doesn’t support Microsoft’s
readyState
property on the XML DOM (indeed,
readyState
isn’t
part of the DOM Level 3 Load and Save specification upon which Mozilla’s implementation is based).
Instead, Mozilla’s XML DOM fires a
load
event when the file has been fully loaded, meaning that you
must use the
onload
event handler to determine when DOM is ready:
oXmlDom.onload = function () {
alert(“Done”);
};
oXmlDom.load(“test.xml”);
Unfortunately, Mozilla’s XML DOM doesn’t support the
loadXML()
method. To parse an XML string
into a DOM, you must use the
DOMParser
object:
var oParser = new DOMParser();
var oXmlDom = oParser.parseFromString(“<root/>”, “text/xml”);
This code creates an XML DOM that represents
<root/>
. The
DOMParser
object is created in the first line,
and the second line uses its only method,
parseFromString()
, to create the XML DOM. This method
accepts two arguments, the XML string to parse and the content type of the string. To parse XML code, the
content type can be
“text/xml”
or
“application/xml”
; any other content type is ignored (although it
is possible to parse XHTML code using the content type
“application/xhtml+xml”
).
Prior to version 1.4, Mozilla only supported asynchronous loading of external files.
In 1.4, Mozilla introduced the
async
property and the capability to load files
synchronously.
451
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 451
Free JavaScript Editor
Ajax Editor
©
→