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>";

An XML DOM parser is created:

parser = new DOMParser();

The parser creates a new XML DOM object using the text string:

xmlDoc = parser.parseFromString(text,"text/xml");

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.