↑
Main Page
Loading XML
using the string in position
i
and assigned it to the variable
oXmlDom
. If that version of the XML DOM
isn’t present on the user ’s machine, it causes an error, which is caught by the
try...catch
statement and
ignored. When that error occurs, the line
return oXmlDom
is completely skipped, and the
for
loop starts
again. Only if the XML DOM object is successfully created is it returned as the function value. If, on the
other hand, each version of the XML DOM is tested and no version is available, the function throws its
own error telling the user that MSXML isn’t installed on the system and processing cannot continue.
By using this function, you can be sure that the XML DOM version you are using is the most recent:
var oXmlDom = createXMLDOM();
Loading XML
Now that you have an XML DOM object, you load some XML into it. Microsoft’s XML DOM comes with
two methods for loading XML:
loadXML()
and
load()
.
The
loadXML()
method enables you to enter an XML string directly into the XML DOM:
oXmlDom.loadXML(“<root><child/></root>”);
The
load()
method is used to load an XML file from the server. Rather, the
load()
method can load an
XML file stored on the same server as the page that contains the JavaScript, meaning that you can’t load
XML from someone else’s server.
There are two modes of loading a file: synchronous and asynchronous. When you load a file in syn-
chronous mode, the JavaScript code waits for the file to be fully loaded before executing the next line of
code; a file loaded in asynchronous mode won’t wait, so you need to use an event handler to determine
when the file has been fully loaded.
By default, files are loaded asynchronously. To set files to load synchronously, just set the
async
prop-
erty to
false
:
oXmlDom.async = false;
You can then use the
load()
method by passing in the name of the file to load:
oXmlDom.load(“test.xml”);
After this line executes,
oXmlDom
contains a DOM Document representing the XML file, so you can use
all the DOM properties and methods:
alert(“Tag name of the root element is “ + oXmlDom.documentElement.tagName);
alert(“The root element has this many children: “ +
oXmlDom.documentElement.childNodes.length);
The code to create an XML DOM in Internet Explorer causes an error in any other
browser. Therefore, you must do a browser detect before attempting to create the
XML DOM in this way.
447
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 447
Free JavaScript Editor
Ajax Editor
©
→