How to Use JS to read XML files

Source: Internet
Author: User
The method for reading XML files using JS Because xml needs to be parsed on the project, Baidu summarized the xml parsing methods of various mainstream browsers, he can only be very simple to know his usage, but there is no in-depth research.

Different browsers use different xml parsing methods. Currently, there are roughly three types of mainstream browsers:

First, the ie ancestor: js provides a method for creating Automation objects, new ActiveXObject ("Microsoft. XMLDOM ");

Class 2: firefox and opera: instantiate the DOMParser object with the constructor DOMParser (), parse the xml text, and return the xml Document object;

Category 3: chrome and safari: Because chrome does not support the load method, the http protocol and XMLHttpRequest object are used.

Code:

Function loadXML () {var xmlDoc; try {// IExmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");} catch (e) {// firefox, operaxmlDoc = document. implementation. createDocument ("", "", null);} try {xmlDoc. asyc = false; // whether to asynchronously call xmlDoc. load ("xxx. xml "); // file path} catch (e) {// chromevar xmlhttp = new window. XMLHttpRequest (); xmlhttp. open ("GET", "xxx. xml ", false); // create a new http request, and specify the request method, URL, and authentication information xmlDoc = xmlhttp. responseXML;} return xmlDoc ;}

The returned xmlDoc object. The property documentElement contains various values of the xml node, which can be found on the console.

Ps: If you are reading local xml files, chrome prohibits access to local files by default. You need to add the startup parameter -- allow-file-access-from-files.

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.