Represents an entire XML document and provides possibilities for accessing, creating and manipulating all elements in the document.
The following methods are supported to create and build an XMLDocument object:
If you want to create a new empty XMLDocument object, use the createDocument method.
Although the createDocument method is supported in Internet Explorer from version 9, but it creates an HTML document, not an XML document.
In Internet Explorer, use the MSXML.DOMDocument ActiveX object to create an XML document.
See Example 1 and the CreateXMLDocumentObject and CreateMSXMLDocumentObject methods in the ajax.js file attached to the example for details.
If you want to build an XMLDocument object from a string, use the DOMParser object.
The DOMParser object is not supported in Internet Explorer before version 9.
In those browsers, create a new XMLDocument object first, then build its contents with the loadXML method.
If you want to build an XMLDocument object from a file or from a response of an HTTP request, use the open method and the responseXML property of the XMLHttpRequest object.
Another possibility to load an XML file is to use the load method of the XMLDocument object.
In Internet Explorer, XML documents can also be embedded into HTML documents with the xml HTML elements.
To get an XMLDocument object that represents the embedded XML data island, use the XMLDocument property of the xml element.
Note that the support for the XMLDocument property has been removed in Internet Explorer 9.
Since the XMLDocument object is a container object for an XML document, it provides methods to create new elements (createElement), text nodes (createTextNode) and comment nodes (createComment).
After a node is created, it can be inserted into the document with the setAttributeNodeNS and setNamedItemNS methods.
If you want to get the root element of an XML document, use the documentElement property.
If a node that belongs to another document needs to be inserted into the current XML document, then it must be imported first (adoptNode and importNode methods).
Occurs when the load state of the XMLDocument object changes.
Example HTML code 1:
This example shows how to create an empty XML document and fill its contents with synchronous loading. For asynchronous loading, see the examples for the async property.
Code
ajax.js
news.xml
<head><scripttype="text/javascript"src="ajax.js"></script><scripttype="text/javascript">var xmlDoc = null;
function LoadXML () {
xmlDoc = CreateXMLDocumentObject (); // defined in ajax.js
if (!xmlDoc) {
return;
}
var url = "news.xml";
xmlDoc.async = true;
if (xmlDoc.addEventListener) {
xmlDoc.addEventListener("load", OnLoadXML, false);
}
else {
xmlDoc.onreadystatechange = OnStateChange;
}
xmlDoc.load (url);
}
function OnLoadXML () {
FillTable ();
}
function OnStateChange () {
if (xmlDoc.readyState == 0 || xmlDoc.readyState == 4) {
FillTable ();
}
}
function FillTable () {
var errorMsg = null;
if (xmlDoc.parseError && xmlDoc.parseError.errorCode != 0) {
errorMsg = "XML Parsing Error: " + xmlDoc.parseError.reason
+ " at line " + xmlDoc.parseError.line
+ " at position " + xmlDoc.parseError.linepos;
}
else {
if (xmlDoc.documentElement) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorMsg = xmlDoc.documentElement.childNodes[0].nodeValue;
}
}
}
if (errorMsg) {
alert (errorMsg);
returnnull;
}
var resTable = document.getElementById ("resTable");
var xmlNodes = ["title", "description", "pubDate", "link"];
var itemTags = xmlDoc.getElementsByTagName ("item");
for (i = 0; i < itemTags.length; i++) {
resTable.insertRow (i);
for (j = 0; j < xmlNodes.length; j++) {
var recordNode = itemTags[i].getElementsByTagName (xmlNodes[j])[0];
resTable.rows[i].insertCell (j);
if ('textContent'in recordNode)
resTable.rows[i].cells[j].innerHTML = recordNode.textContent;
else
resTable.rows[i].cells[j].innerHTML = recordNode.text;
}
}
}
</script></head><bodyonload="LoadXML ()"><tableborder="1px"><theadstyle="font-weight: bold;"><tr><td>Title</td><td>Description</td><td>PubDate</td><td>Link</td></tr></thead><tbodyid="resTable"></tbody></table></body>
function CreateHTTPRequestObject () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
returnnull;
}
function CreateMSXMLDocumentObject () {
if (typeof (ActiveXObject) != "undefined") {
var progIDs = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"Msxml2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument"
];
for (var i = 0; i < progIDs.length; i++) {
try {
returnnewActiveXObject(progIDs[i]);
} catch(e) {};
}
}
returnnull;
}
function CreateXMLDocumentObject (rootName) {
if (!rootName) {
rootName = "";
}
var xmlDoc = CreateMSXMLDocumentObject ();
if (xmlDoc) {
if (rootName) {
var rootNode = xmlDoc.createElement (rootName);
xmlDoc.appendChild (rootNode);
}
}
else {
if (document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument ("", rootName, null);
}
}
return xmlDoc;
}
function ParseHTTPResponse (httpRequest) {
var xmlDoc = httpRequest.responseXML;
// if responseXML is not valid, try to create the XML document from the responseText property
if (!xmlDoc || !xmlDoc.documentElement) {
if (window.DOMParser) {
var parser = newDOMParser();
try {
xmlDoc = parser.parseFromString (httpRequest.responseText, "text/xml");
} catch (e) {
alert ("XML parsing error");
returnnull;
};
}
else {
xmlDoc = CreateMSXMLDocumentObject ();
if (!xmlDoc) {
returnnull;
}
xmlDoc.loadXML (httpRequest.responseText);
}
}
// if there was an error while parsing the XML document
var errorMsg = null;
if (xmlDoc.parseError && xmlDoc.parseError.errorCode != 0) {
errorMsg = "XML Parsing Error: " + xmlDoc.parseError.reason
+ " at line " + xmlDoc.parseError.line
+ " at position " + xmlDoc.parseError.linepos;
}
else {
if (xmlDoc.documentElement) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorMsg = xmlDoc.documentElement.childNodes[0].nodeValue;
}
}
}
if (errorMsg) {
alert (errorMsg);
returnnull;
}
// ok, the XML document is valid
return xmlDoc;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?xmlversion="1.0"encoding="utf-8"?><news><channel><item><title>Paula Abdul leaves American Idol</title><description>Paula Abdul has officially confirmed that she won’t be returning to American Idol this season. "With sadness in my heart, I’ve decided not to return to Idol," she wrote on her Twitter page.</description><pubDate>Wed, August 5, 2009 19:52:31 +0200</pubDate><link>http://www.tribute.ca/news/index.php/its-official-paula-abdul-leaves-american-idol/2009/08/05/</link></item><item><title>Criminal Minds star Moore hit by car</title><description>Shemar Moore, 39, who plays FBI Agent Derek Morgan in the CBS drama Criminal Minds, was hit by a car while bicycling in Los Angeles last Saturday.</description><pubDate>Thu, August 4, 2009 13:28:12 +0200</pubDate><link>http://www.tribute.ca/news/index.php/criminal-minds-star-moore-hit-by-car/2009/08/04/</link></item><item><title>Madonna writes love song for ex-husband</title><description>Madonna has sparked speculation that she wants to get back with her ex-husband, Guy Ritchie, after writing a love song for him in which she calls him her "eternal love".</description><pubDate>Fri, July 31, 2009 04:01:50 +0200</pubDate><link>http://www.tribute.ca/news/index.php/madonna-writes-love-song-for-ex-husband/2009/07/31/</link></item></channel></news>
This example shows how to use the XMLHttpRequest object to create an XMLDocument object. It uses asynchronous operation. For synchronous transfer, see the examples for the open method.
Code
ajax.js
news.xml
<head><scripttype="text/javascript"src="ajax.js"></script><scripttype="text/javascript">var httpRequest = null;
function SendRequest () {
if (!httpRequest) {
httpRequest = CreateHTTPRequestObject (); // defined in ajax.js
}
if (httpRequest) {
// The requested file must be in the same domain that the page is served from.
var url = "news.xml";
httpRequest.open ("GET", url, true); // async
httpRequest.onreadystatechange = OnStateChange;
httpRequest.send (null);
}
}
function OnStateChange () {
if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
if (IsRequestSuccessful (httpRequest)) { // defined in ajax.js
FillTable ();
}
else {
alert ("Operation failed.");
}
}
}
function FillTable () {
var xmlDoc = ParseHTTPResponse (httpRequest); // defined in ajax.js
if (!xmlDoc)
return;
var resTable = document.getElementById ("resTable");
var xmlNodes = ["title", "description", "pubDate", "link"];
var itemTags = xmlDoc.getElementsByTagName ("item");
for (i = 0; i < itemTags.length; i++) {
resTable.insertRow (i);
for (j = 0; j < xmlNodes.length; j++) {
var recordNode = itemTags[i].getElementsByTagName (xmlNodes[j])[0];
resTable.rows[i].insertCell (j);
if ('textContent'in recordNode)
resTable.rows[i].cells[j].innerHTML = recordNode.textContent;
else
resTable.rows[i].cells[j].innerHTML = recordNode.text;
}
}
}
</script></head><bodyonload="SendRequest ()"><tableborder="1px"><theadstyle="font-weight: bold;"><tr><td>Title</td><td>Description</td><td>PubDate</td><td>Link</td></tr></thead><tbodyid="resTable"></tbody></table></body>
function CreateHTTPRequestObject () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
returnnull;
}
function CreateMSXMLDocumentObject () {
if (typeof (ActiveXObject) != "undefined") {
var progIDs = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"Msxml2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument"
];
for (var i = 0; i < progIDs.length; i++) {
try {
returnnewActiveXObject(progIDs[i]);
} catch(e) {};
}
}
returnnull;
}
function CreateXMLDocumentObject (rootName) {
if (!rootName) {
rootName = "";
}
var xmlDoc = CreateMSXMLDocumentObject ();
if (xmlDoc) {
if (rootName) {
var rootNode = xmlDoc.createElement (rootName);
xmlDoc.appendChild (rootNode);
}
}
else {
if (document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument ("", rootName, null);
}
}
return xmlDoc;
}
function ParseHTTPResponse (httpRequest) {
var xmlDoc = httpRequest.responseXML;
// if responseXML is not valid, try to create the XML document from the responseText property
if (!xmlDoc || !xmlDoc.documentElement) {
if (window.DOMParser) {
var parser = newDOMParser();
try {
xmlDoc = parser.parseFromString (httpRequest.responseText, "text/xml");
} catch (e) {
alert ("XML parsing error");
returnnull;
};
}
else {
xmlDoc = CreateMSXMLDocumentObject ();
if (!xmlDoc) {
returnnull;
}
xmlDoc.loadXML (httpRequest.responseText);
}
}
// if there was an error while parsing the XML document
var errorMsg = null;
if (xmlDoc.parseError && xmlDoc.parseError.errorCode != 0) {
errorMsg = "XML Parsing Error: " + xmlDoc.parseError.reason
+ " at line " + xmlDoc.parseError.line
+ " at position " + xmlDoc.parseError.linepos;
}
else {
if (xmlDoc.documentElement) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorMsg = xmlDoc.documentElement.childNodes[0].nodeValue;
}
}
}
if (errorMsg) {
alert (errorMsg);
returnnull;
}
// ok, the XML document is valid
return xmlDoc;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?xmlversion="1.0"encoding="utf-8"?><news><channel><item><title>Paula Abdul leaves American Idol</title><description>Paula Abdul has officially confirmed that she won’t be returning to American Idol this season. "With sadness in my heart, I’ve decided not to return to Idol," she wrote on her Twitter page.</description><pubDate>Wed, August 5, 2009 19:52:31 +0200</pubDate><link>http://www.tribute.ca/news/index.php/its-official-paula-abdul-leaves-american-idol/2009/08/05/</link></item><item><title>Criminal Minds star Moore hit by car</title><description>Shemar Moore, 39, who plays FBI Agent Derek Morgan in the CBS drama Criminal Minds, was hit by a car while bicycling in Los Angeles last Saturday.</description><pubDate>Thu, August 4, 2009 13:28:12 +0200</pubDate><link>http://www.tribute.ca/news/index.php/criminal-minds-star-moore-hit-by-car/2009/08/04/</link></item><item><title>Madonna writes love song for ex-husband</title><description>Madonna has sparked speculation that she wants to get back with her ex-husband, Guy Ritchie, after writing a love song for him in which she calls him her "eternal love".</description><pubDate>Fri, July 31, 2009 04:01:50 +0200</pubDate><link>http://www.tribute.ca/news/index.php/madonna-writes-love-song-for-ex-husband/2009/07/31/</link></item></channel></news>
This example contains an XML data island inside an HTML document and uses the XMLDocument property to get an XMLDocument object that represents the embedded data. This example does not work in Internet Explorer from version 9, because the support for the XMLDocument property was removed.
<head><scripttype="text/javascript">function DisplayXMLIsland () {
var xmlIsland = document.getElementById ("xmlIsland");
if (xmlIsland.XMLDocument) {
alert (xmlIsland.XMLDocument.xml);
}
else {
alert ("Your browser doesn't support the XMLDocument property.");
}
}
</script></head><body><xmlid="xmlIsland"><movie><name>Clark Kent</name><jobtitle>Superman</jobtitle><born>1966</born></movie></xml><buttononclick="DisplayXMLIsland ()">Get the contents of the XML island</button></body>