Latest web development tutorials

XML DOM parser

Most browsers are built for reading and manipulating XML XML parser.

XML parser to convert JavaScript objects accessible (XML DOM).


XML parser

XML DOM contains the XML tree traversal, access, insert and delete nodes method (function).

However, before accessing and manipulating XML documents, it must be loaded into the XML DOM object.

XML parser reads the XML, and convert it to XML DOM object, so that it can use JavaScript to access it.

Most browsers have a built-in XML parser.


Load an XML document

The following JavaScript fragment loads an XML document ( " the Books.xml "):

Examples

if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

try it"

Code explanation:

  • Create a XMLHTTP object
  • Open the XMLHTTP object
  • Send an XML HTTP request to the server
  • Setting the response is XML DOM object

Loading XML string

The following code loads and parses an XML string:

Examples

if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}

try it"

Note: Internet Explorer use loadXML () method to parse an XML string, while other browsers use DOMParser object.


Cross-domain access

For security reasons, modern browsers do not allow cross-domain access.

This means that web pages, and XML file, it tries to load must be located on the same server.

Examples W3CSchool on all open XML files are located on W3CSchool domain.

If you want to use the example above on your web page, XML files you load must be located on your own server.