You are here: Reference > JavaScript > client-side > xml handling > objects > XMLDocument

XMLDocument object

Browser support:
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 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).

Syntax:

Properties that reference the object:
XMLHttpRequest.responseXML
xml.XMLDocument
Methods that return the object:
implementation.createDocument (namespaceURI, qualifiedName, docTypeObj)
DOMParser.parseFromBuffer (buffer, bufferLength, mimeType)
DOMParser.parseFromStream (stream, charset, contentLength, mimeType)
DOMParser.parseFromString (xmlString, mimeType)
The base interface, through which you can add new functionalities to the XMLDocument object, is the XMLDocument interface.

Possible members:

Properties
Methods
Events
async
Specifies or retrieves whether downloading an XML file should be performed asynchronously or not.
attributes
Represents a collection of attribute nodes that belong to an element.
baseURI
10
Returns the base URL for the object.
characterSet
Returns the character encoding of the document.
charset
Sets or retrieves the character encoding of the document, a linked document or a script block.
childNodes
Represents a collection of all nodes that are direct descendants of an element.
contentType
Sets or retrieves the MIME type of the current document.
defaultView
Retrieves a reference to the default AbstractView object for the current document.
dir
Sets or retrieves the horizontal rendering order in the current document.
doctype
Represents a Document Type Definition (DTD).
documentElement
Returns a reference to the root element node of the document.
documentURI
Sets or returns the absolute location of the document.
firstChild
Returns a reference to the first child of the current element.
implementation
Contains information about the features supported by the browser and provides methods for creating base objects.
inputEncoding
Returns the character encoding used for parsing the document.
lastChild
Returns a reference to the last child of the current element.
lastModified
Retrieves the date and time when the document was last modified.
location
Contains information about the URL of the currently loaded document, and provides methods to navigate to a new page.
namespaces
Represents a collection of namespaces that have been declared for custom elements in HTML.
nextSibling
Returns a reference to the next child of the current element's parent.
nodeName
Returns the name of the current node.
nodeType
Returns an integer that indicates the type of the node.
nodeTypeString
Returns the type of the current node as a string.
nodeValue
Sets or returns the value of the current node.
parentNode
Returns the parent element of the current node in the DOM hierarchy.
parseError
Contains detailed information about the error of the last XML parsing.
previousSibling
Returns a reference to the previous node of the current element's parent.
readyState
Returns an integer value that indicates the load state of the XMLDocument object.
referrer
Retrieves the URL of the document that loaded the current page.
styleSheets
Represents a collection of styleSheet objects in the current document.
title
Sets or returns the title of the current document.
URL
Specifies or returns the location of the current document.
xml
Returns the node and its descendants as a string.
xmlEncoding
Returns the character encoding of the XMLDocument.
xmlStandalone
Returns whether the XMLDocument is standalone.
xmlVersion
Returns the version of the XMLDocument as a string.

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>
    <script type="text/javascript" src="ajax.js"></script>
    
    <script type="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);
                return null;
            }

            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>
<body onload="LoadXML ()">
    <table border="1px">
        <thead style="font-weight: bold;">
            <tr>
                <td>Title</td>
                <td>Description</td>
                <td>PubDate</td>
                <td>Link</td>
            </tr>
        </thead>
        <tbody id="resTable">
        </tbody>
    </table>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

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>
    <script type="text/javascript" src="ajax.js"></script>
    
    <script type="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>
<body onload="SendRequest ()">
    <table border="1px">
        <thead style="font-weight: bold;">
            <tr>
                <td>Title</td>
                <td>Description</td>
                <td>PubDate</td>
                <td>Link</td>
            </tr>
        </thead>
        <tbody id="resTable">
        </tbody>
    </table>
</body>
Did you find this example helpful? yes no

Example HTML code 3:

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>
    <script type="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>
    <xml id="xmlIsland">
        <movie>
            <name>Clark Kent</name>
            <jobtitle>Superman</jobtitle>
            <born>1966</born>
        </movie>
    </xml>
    <button onclick="DisplayXMLIsland ()">Get the contents of the XML island</button>
</body>
Did you find this example helpful? yes no

Related pages:

External links:

User Contributed Comments

Post Content

Post Content