Main Page

Retrieving XML

Retrieving XML
After you’ve gotten XML into a DOM, it’s logical to assume you must be able to get that XML back out.
Microsoft made this easy by adding an
xml
property for every node, including a document node, which
returns its representative XML code as a string. So to retrieve the XML that you just loaded is simple:
oXmlDom.load(“test.xml”);
alert(oXmlDom.xml);
You can also retrieve the XML for a particular node:
var oNode = oXmlDom.documentElements.childNodes[1];
alert(oNode.xml);
The
xml
property is read-only and causes an error if you try to assign a value to it.
Parsing errors
When you try to load XML into an XML DOM object, whether by using
loadXML()
or
load()
, there’s
the possibility that the XML isn’t well-formed. To provide for this, the Microsoft XML DOM has a prop-
erty called
parseError
that contains all the information about any errors encountered while parsing
XML code.
The
parseError
property is actually an object with the following properties:
?
errorCode
— Numeric code indicating the type of error that occurred (0 when there’s no error)
?
filePos
— Position within the file where the error occurred
?
line
— The line on which the error occurred
?
linepos
– The character on the line where the error occurred
?
reason
— A plain text explanation of the error
?
srcText
— The code that caused the error
?
url
— The URL of the file that caused the error (if available)
When the
parseError
property is used by itself, it returns the value of
errorCode
, meaning that you
can check for errors by doing this:
if (oXmlDom.parseError != 0) {
//there were errors, do something about it here
}
Always check that the error code is not equal to 0, rather than if it’s greater than or less than 0, because
error codes can be either positive or negative.
You can use the
parseError
object to create your own error dialogs:
if (oXmlDom.parseError != 0) {
var oError = oXmlDom.parseError;
alert(“An error occurred:\nError Code: “
449
XML in JavaScript
18_579088 ch15.qxd 3/28/05 11:42 AM Page 449


JavaScript EditorFree JavaScript Editor     Ajax Editor


©