XML Parser
- Previous Page XML HttpRequest
- Next Page XML DOM
All mainstream browsers have built-in XML parsers for accessing and manipulating XML.
The parser converts XML to XML DOM objects - objects that can be manipulated through JavaScript.
XML Parser
XML DOM (Document Object Model)Properties and methods defined for accessing and editing XML.
However, before accessing the XML document, it must be loaded into an XML DOM object.
All modern browsers provide built-in XML parsers that can convert text to XML DOM objects.
Parse text string
This example parses the text string into an XML DOM object and uses JavaScript to extract information from it:
Example
<html> <body> <p id="demo"></p> <script> var text, parser, xmlDoc; text = "<bookstore><book>" "<title>雅舍谈吃</title>" + "<author>梁实秋</author>" + "<year>2013</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 explanation
Define text string:
text = "<bookstore><book>" "<title>雅舍谈吃</title>" + "<author>梁实秋</author>" + "<year>2013</year>" + "</book></bookstore>"
Create XML DOM parser:
parser = new DOMParser();
The parser used this text string to create a new XML DOM object:
xmlDoc = parser.parseFromString(text,"text/xml");
XMLHttpRequest object
XMLHttpRequest objectProvide built-in XML parser.
responseText
property to return the response in string format.
responseXML
property to return the response in the form of an XML DOM object.
If you want to use the response as an XML DOM object, you can use responseXML
property.
Example
Request file cd_catalog.xmlAnd 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;
- Previous Page XML HttpRequest
- Next Page XML DOM