Parse XML files and XML strings in JS, parse xml strings in js

Source: Internet
Author: User

Parse XML files and XML strings in JS, parse xml strings in js

Parse XML files using JS

<Script type = 'text/javascript '> loadXML = function (xmlFile) {var xmlDoc = null; // you can determine the type of the browser. // if (! Window. DOMParser & window. activeXObject) {var xmlDomVersions = ['msxml. 2. DOMDocument.6.0 ', 'msxml. 2. DOMDocument.3.0 ', 'Microsoft. XMLDOM ']; for (var I = 0; I <xmlDomVersions. length; I ++) {try {xmlDoc = new ActiveXObject (xmlDomVersions [I]); break;} catch (e) {}}// supports Mozilla else if (document. implementation & document. implementation. createDocument) {try {/* document. implementation. createDocument ('','', null); three parameters of the Method Description * The first parameter is a string containing the namespace URI used by the document; * The second parameter is a string containing the name of the document root element; * The third parameter is the document type to be created (also called doctype) */xmlDoc = document. implementation. createDocument ('','', null);} catch (e) {}} else {return null;} if (xmlDoc! = Null) {xmlDoc. async = false; xmlDoc. load (xmlFile) ;}return xmlDoc ;}</script>

Parse XML strings using JS

<Script type = 'text/javascript '> loadXML = function (xmlString) {var xmlDoc = null; // you can determine the type of the browser. // if (! Window. DOMParser & window. activeXObject) {// window. DOMParser determines whether it is a non-iebrowser var xmlDomVersions = ['msxml. 2. DOMDocument.6.0 ', 'msxml. 2. DOMDocument.3.0 ', 'Microsoft. XMLDOM ']; for (var I = 0; I <xmlDomVersions. length; I ++) {try {xmlDoc = new ActiveXObject (xmlDomVersions [I]); xmlDoc. async = false; xmlDoc. loadXML (xmlString); // loadXML method load xml string break;} catch (e) {}}// supports Mozilla else if (window. DOMParser & document. implem Entation & document. implementation. createDocument) {try {/* DOMParser object parses the XML text and returns an XML Document object. * To use DOMParser, use a constructor without parameters to instantiate it, and then call its parseFromString () method * parseFromString (text, contentType) parameter text: the content type of the XML tag parameter contentType text to be parsed * may be one of "text/xml", "application/xml", or "application/xhtml + xml. Note: "text/html" is not supported ". */DomParser = new DOMParser (); xmlDoc = domParser. parseFromString (xmlString, 'text/xml');} catch (e) {}} else {return null;} return xmlDoc ;}</script>

Test XML

<?xml version="1.0" encoding="utf-8" ?><DongFang><Company><cNname>1</cNname><cIP>1</cIP></Company><Company><cNname>2</cNname><cIP>2</cIP></Company><Company><cNname>3</cNname><cIP>3</cIP></Company><Company><cNname>4</cNname><cIP>4</cIP></Company><Company><cNname>5</cNname><cIP>5</cIP></Company><Company><cNname>6</cNname><cIP>6</cIP></Company></DongFang>

Usage

var xmldoc=loadXML(text.xml)var elements = xmlDoc.getElementsByTagName("Company");for (var i = 0; i < elements.length; i++) {var name = elements[i].getElementsByTagName("cNname")[0].firstChild.nodeValue;var ip = elements[i].getElementsByTagName("cIP")[0].firstChild.nodeValue;}

The above method is suitable for IE. Next we will discuss the XML parsing problem in IE and Firefox browsers.

Parse the xml document and xml string for ie and Firefox respectively. All the code has been commented out. Which of the following functions do you want to see,
Just remove the comment.

As for xml parsing in the ajax environment, the principle is the same, but the xml returned must be parsed In the ajax environment.

<Script> // parse the xml document //////////////////////////////// /// // var xmlDoc = null; // supports ie Explorer if (window. activeXObject) {xmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");} // supports Mozilla else if (document. implementation & document. implementation. createDocument) {xmlDoc = document. implementation. createDocument ('','', null);} else {alert ("here");} if (xmlDoc! = Null) {xmlDoc. async = false; xmlDoc. load ("house. xml");} // ie and Firefox are different not only in the parser, but also in the parsing process. As follows; // ie parses the xml document // alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [0]. childNodes [0]. childNodes [0]. nodeValue); // The 1.5 million // alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // a three-bedroom window is displayed. // layer-by-layer traversal parsing childNodes [1] // alert (xmlDoc. childNodes [1]. childNodes [1]. childNodes [0]. childNodes [0]. nodeValue); // the 2 million // alert (xmlDoc. childNodes [1]. childNodes [0]. child Nodes [0]. childNodes [0]. nodeValue); // The 1.5 million // alert (xmlDoc. childNodes [1]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // you can use item (I) to traverse the three residences in one room. // var nodes?xmldoc.doc umentElement. childNodes; // alert (nodes. item (0 ). childNodes. item (0 ). childNodes. item (0 ). text); // The 1.5 million // alert (nodes. item (0 ). childNodes. item (1 ). childNodes. item (0 ). text); // The trigger room is three homes // Firefox parses the xml document // Firefox and ie parse the xml node values using textContent. // And it will add the "\ n" line break before and after some child nodes. (I don't know why. It looks like this when debugging with firebug, so it is best to test the code that has been written. It is wrong to change the environment) // That is to say, 1st nodes are \ n, and 2nd nodes are the real first node. // 3rd nodes are \ n, and 4th nodes are the real second node. // Retrieve and parse childNodes [0] // alert (xmlDoc. childNodes [0]. childNodes [1]. childNodes [1]. textContent); // The 1.5 million // alert (xmlDoc. childNodes [0]. childNodes [1]. childNodes [3]. textContent); // The third-bedroom dialog box is displayed. // get the node name directly. parse getElementsByTagName ("address") // alert (xmlDoc. getElementsByTagName ("address") [0]. textContent); // pop up room 1.5 million, three homes 2 million 3 million // alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. textContent); // pop up 1.5 million, one room, three residences // Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. childNodes [1]. textContent); // The 1.5 million // alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. childNodes [3]. textContent); // The third-bedroom dialog box is displayed. // alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [3]. textContent); // pop-up 2 million // Firefox can also be traversed using the item (1) function. Note that node "\ n" is added before and after some hierarchical nodes ". // The first node is item (1), the second node is item (3), and the third node is item (5) // item (1) function traversal parsing // var nodes‑xmldoc.doc umentElement. childNodes; // alert (nodes. item (1 ). textContent); // The third-bedroom, third-bedroom, 1.5 million is displayed. // alert (nodes. item (1 ). childNodes. item (1 ). textContent); // The 1.5 million // alert (nodes. item (1 ). childNodes. item (3 ). textContent ); // three-bedroom one/three-bedroom parsing xml string ////////////////////////////// //////////////////////////////////////// /// var str = "<car>" + "<brand> <price> 5 0 thousand </price> <pattern> A6 </pattern> </brand> "+" <brand> <price> 0.65 million </price> <pattern> A8 </pattern> </brand> "+" <brand> <price> 0.17 million </price> </brand> "+" </car> "; // cross-browser, the parser used by ie and Firefox for parsing xml is different. Var xmlStrDoc = null; if (window. DOMParser) {// Mozilla Explorer parser = new DOMParser (); xmlStrDoc = parser. parseFromString (str, "text/xml");} else {// Internet Explorer xmlStrDoc = new ActiveXObject ("Microsoft. XMLDOM "); xmlStrDoc. async = "false"; xmlStrDoc. loadXML (str);} // ie parses the xml string // alert (xmlStrDoc. getElementsByTagName ("car") [0]. childNodes [0]. childNodes [0]. childNodes [0]. nodeValue); // The 0.5 million // alert (xmlStr Doc. getElementsByTagName ("car") [0]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // A6 // you can also use item (I) to traverse // var strnodes1_xmlstrdoc.doc umentElement. childNodes; // alert (strNodes. item (0 ). childNodes. item (0 ). childNodes. item (0 ). text); // The 0.5 million // alert (strNodes. item (0 ). childNodes. item (1 ). childNodes. item (0 ). text); // pop-up A6 // Firefox parses the xml string // Firefox and ie parse the value of different nodes using textContent. // And it will add the "\ n" line break before and after some child nodes. // That is to say, 1st nodes are \ n, and 2nd nodes are the real first node. // 3rd nodes are \ n, and 4th nodes are the real second node. // Alert (xmlStrDoc. childNodes [0]. childNodes [1]. textContent); // The 0.65 million A8 // alert (xmlStrDoc. childNodes [0]. childNodes [1]. childNodes [1]. textContent); // A8 // alert (xmlStrDoc. childNodes [0]. childNodes [1]. childNodes [0]. textContent); // pop-up 0.65 million // Firefox can also be traversed using the item (1) function. Note that node "\ n" is added before and after some hierarchical nodes ". // The first node is item (1), the second node is item (3), and the third node is item (5) // var nodes1_xmlstrdoc.doc umentElement. childNodes; // alert (nodes. item (1 ). textContent); // The 0.65 million A8 // alert (nodes. item (1 ). childNodes. item (0 ). textContent); // The 0.65 million // alert (nodes. item (1 ). childNodes. item (1 ). textContent); // pop up A8 </script>

The layer of each xml node is the most annoying problem. You can only try it again and again,
Determine the node hierarchy, or debug it.
I feel that json is better able to read and understand this aspect. This parsing is too hard!

The document house. xml is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Address> <city name = "Beijing"> <price> 1.5 million </price> <type> one-bedroom, three-bedroom </type> </city> <city name = "Shanghai"> <price> 2 million </price> </city> <city name = "Hangzhou"> <price> 2.3 million </price> </city> <city name = "Nanjing"> </city> </address>

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.