18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15<br />

452<br />

Because the XML DOM is part of Mozilla’s <strong>JavaScript</strong> implementation, it is possible to add a loadXML()<br />

method. The actual class for the XML DOM is called Document, so adding a new method is as easy as<br />

using the prototype object:<br />

Document.prototype.loadXML = function (sXml) {<br />

//function body<br />

};<br />

Then, use the DOMParser to create a new XML DOM:<br />

Document.prototype.loadXML = function (sXml) {<br />

};<br />

var oParser = new DOMParser();<br />

var oXmlDom = oParser.parseFromString(sXml, “text/xml”);<br />

//...<br />

Next, the original document must be emptied of its contents. You can do this by using a while loop and<br />

removing all the document’s child nodes:<br />

Document.prototype.loadXML = function (sXml) {<br />

};<br />

var oParser = new DOMParser();<br />

var oXmlDom = oParser.parseFromString(sXml, “text/xml”);<br />

while (this.firstChild) {<br />

this.removeChild(this.firstChild);<br />

}<br />

//...<br />

Remember, because this function is a method, the this keyword refers to the XML DOM object. After all<br />

the children have been removed, all the children of oXmlDom must be imported into the document (using<br />

importNode()) and added as children (using appendChild()):<br />

Document.prototype.loadXML = function (sXml) {<br />

};<br />

var oParser = new DOMParser();<br />

var oXmlDom = oParser.parseFromString(sXml, “text/xml”);<br />

while (this.firstChild) {<br />

this.removeChild(this.firstChild);<br />

}<br />

for (var i=0; i < oXmlDom.childNodes.length; i++) {<br />

var oNewNode = this.importNode(oXmlDom.childNodes[i], true);<br />

this.appendChild(oNewNode);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!