Example code for reading xml files in JS in IE _ javascript skills

Source: Internet
Author: User
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.
Related Article

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.