The specific steps for JS to read xml files are as follows: Create DOM objects, load xml files (for IE only), and add sample code. If you are interested, refer, I hope it will be helpful for you to use JS to read xml files. Here, only the IE browser is considered.
Step 1 create a DOM object
The Code is as follows:
Function createDom (){
Var xmlDoc = null;
Try {// IE
If (typeof arguments. callee. activeXString! = 'String '){
Var versions = [
"MSXML2.DOMDocument. 6.0 ",
"MSXML2.DOMDocument. 3.0 ",
"MSXML2.DOMDocument ",
"Microsoft. XMLDOM"
];
Var I,
Len;
For (I = 0, len = versions. length; I <len; ++ I ){
Try {
New ActiveXObject (versions [I]);
Arguments. callee. activeXString = versions [I];
Break;
} Catch (ex ){
// Ignore
}
}
}
XmlDoc = new ActiveXObject (arguments. callee. activeXString );
} Catch (ex) {// other
XmlDoc = document. implementation. createDocument ("", "", null );
}
Return xmlDoc;
}
Before IE8, XmlDom was implemented by ActiveX objects. After IE9, IE began to support Level 2 DOM. (other browsers that support Level 2 DOM include Firefox, Opera, Chrome, and Safari)
You can create an xml dom object as follows:
The Code is as follows:
Var xmldom = document. implementation. createDocument (namespaceUri, root, doctype );
Step 2 load the xml file
The Code is as follows:
Function loadXML (file ){
Var dom = createDom ();
If (dom = null ){
Alert ("load filed! ");
}
Try {
Dom. async = false;
Dom. load (file );
} Catch (ex ){
Alert ("unsupport browser! ");
}
Return dom;
}
A simple example:
The Code is as follows:
Var xmlDom = loadXML ("config. xml ");
In IE, you can call the selectNodes () and selectSingleNode () Methods to quickly locate nodes using XPath.