Cross-Browser Javascript XML Parsing

前端 未结 3 2004
梦谈多话
梦谈多话 2020-11-22 08:34

Are there any cross-browser / cross-platform ways to parse XML files in Javascript?

3条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:59

    Consider using jQuery.parseXML.

    Note that old JQuery's code (pre 2.x) is essentially identical to one proposed in the accepted answer and can be found at http://code.jquery.com/jquery-1.9.1.js, partial version below:

    // Cross-browser xml parsing
    parseXML: function( data ) {
        ...
        try {
            if ( window.DOMParser ) { // Standard
                tmp = new DOMParser();
                xml = tmp.parseFromString( data , "text/xml" );
            } else { // IE
                xml = new ActiveXObject( "Microsoft.XMLDOM" );
                xml.async = "false";
                xml.loadXML( data );
            }
        } catch( e ) {
            xml = undefined;
        }
        ...
    }
    

    Starting JQuery 2.x code changed to skip ActiveX branch, if you still need it - use older version of JQuery or inline ActiveX parsing. Partial code from http://code.jquery.com/jquery-2.0.0.js:

    // Cross-browser xml parsing
    parseXML: function( data ) {
        var xml, tmp;
        .....
        // Support: IE9
        try {
            tmp = new DOMParser();
            xml = tmp.parseFromString( data , "text/xml" );
        } catch ( e ) {
            xml = undefined;
        }
        .....
    },
    

提交回复
热议问题