Parser XML

Wszystkie główne przeglądarki mają wbudowane analizatory XML, używane do dostępu i operacji na XML.

The parser converts XML to an XML DOM object - an object that can be manipulated through JavaScript.

Parser XML

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 a built-in XML parser that can convert text to an XML DOM object.

Parse text string

This example parses a 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>

Spróbuj sam

Example explanation

Define a text string:

text = "<bookstore><book>"
"<title>雅舍谈吃</title>" +
"<author>梁实秋</author>" +
"<year>2013</year>" +
"</book></bookstore>"

Create an XML DOM parser:

parser = new DOMParser();

The parser created a new XML DOM object using this text string:

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

XMLHttpRequest object

XMLHttpRequest objectprovides a built-in XML parser.

responseText property to return the response in string form.

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 properties.

example

request file cd_catalog.xmli\'m using this 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;

Spróbuj sam