Main Page

XML DOM

Because the XML DOM is part of Mozilla’s JavaScript implementation, it is possible to add a
loadXML()
method. The actual class for the XML DOM is called
Document
, so adding a new method is as easy as
using the
prototype
object:
Document.prototype.loadXML = function (sXml) {
//function body
};
Then, use the
DOMParser
to create a new XML DOM:
Document.prototype.loadXML = function (sXml) {
var oParser = new DOMParser();
var oXmlDom = oParser.parseFromString(sXml, “text/xml”);
//...
};
Next, the original document must be emptied of its contents. You can do this by using a
while
loop and
removing all the document’s child nodes:
Document.prototype.loadXML = function (sXml) {
var oParser = new DOMParser();
var oXmlDom = oParser.parseFromString(sXml, “text/xml”);
while (this.firstChild) {
this.removeChild(this.firstChild);
}
//...
};
Remember, because this function is a method, the
this
keyword refers to the XML DOM object. After all
the children have been removed, all the children of
oXmlDom
must be imported into the document (using
importNode()
) and added as children (using
appendChild()
):
Document.prototype.loadXML = function (sXml) {
var oParser = new DOMParser();
var oXmlDom = oParser.parseFromString(sXml, “text/xml”);
while (this.firstChild) {
this.removeChild(this.firstChild);
}
for (var i=0; i < oXmlDom.childNodes.length; i++) {
var oNewNode = this.importNode(oXmlDom.childNodes[i], true);
this.appendChild(oNewNode);
}
};
452
Chapter 15
18_579088 ch15.qxd 3/28/05 11:42 AM Page 452


JavaScript EditorFree JavaScript Editor     Ajax Editor


©