JS parse XML file and XML string detailed _javascript skills

Source: Internet
Author: User

JS Parse XML file

<script type= ' text/javascript ' >
loadxml = function (xmlFile) {
var xmldoc=null;
Determine the type of browser
//support IE browser
if (!window. Domparser && windows. 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) {
}
}
}
//support Mozilla browser
else if (document.implementation && document.implementation.createDocument) {
try{
/* document.implementation.createDocument (",", null); Three parameter description of the method
* 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 type of document to create (also known as DOCTYPE).
xmldoc = Document.implementation.createDocument (",", null);
} catch (E) {
}
}
else{return
null;
}
if (xmldoc!=null) {
Xmldoc.async = false;
Xmldoc.load (XmlFile);
}
return xmldoc;
}
</script>

JS Parse XML string

<script type= ' text/javascript ' > loadxml = function (xmlstring) {var xmldoc=null;//determine browser type//support IE browser if (!window. Domparser && windows. ActiveXObject) {//window. Domparser to determine if the non-IE browser 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);
The Loadxml method loads an XML string break; }catch (e) {}}}//support Mozilla Browser else if window. Domparser && document.implementation && document.implementation.createDocument) {try{/* Domparser
object resolves the XML text and returns an XML Document object. * To use Domparser, instantiate it with a constructor without parameters, and then call its parsefromstring () method * parsefromstring (text, contentType) parameter text: XML tag arguments to parse con The content type of the Tenttype text may be one of the "Text/xml", "Application/xml" or "Application/xhtml+xml".
Note that "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>

How to use

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.nod Evalue;
var ip = elements[i].getelementsbytagname ("CIP") [0].firstchild.nodevalue;
}

The above method is suitable for IE, below we discuss the problem of parsing XML under IE and Firefox browser

respectively for IE and Firefox respectively for XML documents and XML string parsing, all the code is commented out, want to see which part of the function,
Just get rid of the annotations.

As for parsing XML in an AJAX environment, the principle is the same, except in Ajax, or parsing the returned XML.

<script>//Parsing XML documents/////////////////////////////////////////////////////var Xmldoc=null; Supports IE browser if (window.  
ActiveXObject) {xmldoc=new ActiveXObject ("Microsoft.XMLDOM"); //Support Mozilla browser else if (document.implementation && document.implementation.createDocument) {xmldoc = Documen 
T.implementation.createdocument (",", null); 
else{alert ("Here"); 
  } if (xmldoc!=null) {xmldoc.async = false; 
Xmldoc.load ("House.xml"); //ie and Firefox are not the same as the parser, the parsing process is different. 
Following IE parses XML document//alert (Xmldoc.getelementsbytagname ("address") [0].childnodes[0].childnodes[0].childnodes[0]. NodeValue)//pop-up 1.5 million//alert (Xmldoc.getelementsbytagname ("address") [0].childnodes[0].childnodes[1].childnodes[0] NodeValue)//pop-up one-room three-/-layer traversal analysis Childnodes[1]//alert (xmldoc.childnodes[1].childnodes[1].childnodes[0].childnodes[0 ].nodevalue);/Eject 2 million//alert (Xmldoc.childnodes[1].childnodes[0].childnodes[0].childnodes[0].nodevalue); Pop-up 1.5 million//alert (Xmldoc.childnodes[1].childnodes[0].childnodes[1].chiLdnodes[0].nodevalue)//pop-up one room three home//can also use item (i) to traverse//var nodes=xmldoc.documentelement.childnodes; Alert (Nodes.item (0). Childnodes.item (0). Childnodes.item (0). Text); Eject 1.5 million//alert (Nodes.item (0). Childnodes.item (1). Childnodes.item (0). Text); 
Pop up a room three lives//Firefox parsing XML documents//Firefox browser and IE parsing XML node values are textcontent. And he would put "\ n" line breaks before and after the child nodes of the hierarchy. 
(This is not clear why, with the Firebug debugging is the case, so the written code best test, change the environment is wrong)//That is, the 1th node is "\ n", the 2nd node is the real first node. 
The 3rd node is "\ n", and the 4th node is the true second node. Layer get parse Childnodes[0]//alert (xmldoc.childnodes[0].childnodes[1].childnodes[1].textcontent);//Eject 1.5 million//alert ( xmldoc.childnodes[0].childnodes[1].childnodes[3].textcontent)//pop-up one room triple/Direct get node name resolution getElementsByTagName ("address ")//alert (Xmldoc.getelementsbytagname (" address ") [0].textcontent);/pop-up 1,500,001 room three 20.003 billion//alert ( Xmldoc.getelementsbytagname ("Address") [0].childnodes[1].textcontent);/pop up 1,500,001 room three-Habitat//alert ( Xmldoc.getelementsbytagname ("Address") [0].childnodes[1].childnodes[1].textcontent);//Eject 1.5 million//alert ( Xmldoc.getelementsbytagnaMe ("Address") [0].childnodes[1].childnodes[3].textcontent);/pop up one room three//alert (Xmldoc.getelementsbytagname ("Address 
//Pop-up 2 million//Firefox can also use the item (1) Function traversal, note that there are also some hierarchy node before and after the node "\ n". 
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.documentelement.childnodes; Alert (Nodes.item (1). textcontent); Pop up 1,500,001 room triple//alert (Nodes.item (1). Childnodes.item (1). textcontent); Eject 1.5 million//alert (Nodes.item (1). Childnodes.item (3). Textcontent); 
One room, three lives//parse XML string/////////////////////////////////////////////////////////////////////////var str= "<car>" + "<brand><price>50 million </price><pattern>A6</pattern></brand>" + "<brand> &LT;PRICE&GT;65 million </price><pattern>A8</pattern></brand> "+" &LT;BRAND&GT;&LT;PRICE&GT;17 million 
 
</price></brand> "+" </car> "; 
Cross-browsers, IE and Firefox parse XML using the parser is not the same. 
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 Parse XML string//alert (Xmlstrdoc.getelementsbytagname ("Car") [0].childnodes[0].childnodes[0].childnodes[0]. NodeValue);//Eject 500,000//alert (Xmlstrdoc.getelementsbytagname ("Car") [0].childnodes[0].childnodes[1].childnodes[0]. 
NodeValue);//pop-up A6//can also use item (i) to traverse//var strnodes=xmlstrdoc.documentelement.childnodes; Alert (Strnodes.item (0). Childnodes.item (0). Childnodes.item (0). Text); Eject 500,000//alert (Strnodes.item (0). Childnodes.item (1). Childnodes.item (0). Text); 
Pop-up A6//Firefox parse XML string//Firefox browser and IE parse XML differently node values are used Textcontent. 
And he would put "\ n" line breaks before and after the child nodes of the hierarchy. 
That means the 1th node is "\ n", and the 2nd node is the real first node. 
The 3rd node is "\ n", and the 4th node is the true second node. alert (xmlstrdoc.childnodes[0].childnodes[1].textcontent);//Eject 650,000 A8//alert (xmlstrdoc.childnodes[0].childnodes [1].childnodes[1].textcontent);//a8//alert (Xmlstrdoc.childnodes[0].childnodes[1].childnodes[0].textcontent);//Eject 650,000//Firefox can also use the item (1) Function traversal, note that there are also some hierarchy node before and after the node "\ n". 
The first node is item (1), the second node is item (3), and the third node is Item (5)//var nodes=xmlstrdoc.documentelement.childnodes; Alert (Nodes.item (1). textcontent); Pop-up 650,000 A8//alert (Nodes.item (1). Childnodes.item (0). textcontent); Eject 650,000//alert (Nodes.item (1). Childnodes.item (1). textcontent); 
 Pop-up A8 </script>

Where the XML each node level is the most annoying problem, can only try again and again, just come out a right,
It's a good way to determine the level of a node, or debug it.
The sense that JSON is still better read and understand. This parsing is too strenuous!

The document House.xml content is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>  
<address> 
  <city name= "Beijing" > 
    <price>150 million </price> 
    <type> one room triple </type> 
  </city> 
  <city name= "Shanghai" > 
    <price> 2 million </price> 
  </city> 
  <city name= "Hangzhou" > 
    <price>230 million </price> 
  </ city> 
  <city name= "Nanjing" ></city> 

The above mentioned is the entire content of this article, I hope you can enjoy.

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.