XML Parser
All major browsers have a built-in XML parser to access and manipulate XML.
XML Parser
The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML.However, before an XML document can be accessed, it must be loaded into an XML DOM object.
All modern browsers have a built-in XML parser that can convert text into an XML DOM object.
Parsing a Text String
This example parses a text string into an XML DOM object, and extracts the info from it with JavaScript:Example
<html>
<body>
<p id="demo"></p>
<script>
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;</script>
</body>
</html>
Example Explained
A text string is defined:text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
Old Versions of Internet Explorer
Old versions of Internet Explorer (IE5, IE6, IE7, IE8) do not support the DOMParser object.To handle older versions of Internet Explorer, check if the browser supports the DOMParser object, or else create an ActiveXObject:
Example
if (window.DOMParser) {
// code for modern browsers parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
} else {
// code for old IE browsersxmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(text);
}
The XMLHttpRequest Object
The XMLHttpRequest Object has a built in XML Parser.The responseText property returns the response as a string.
The responseXML property returns the response as an XML DOM object.
If you want to use the response as an XML DOM object, you can use the responseXML property.
Example
Request the file cd_catalog.xml and use the response as an XML DOM object:xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;