$.parseXML cannot parse XML with script tag inside

感情迁移 提交于 2019-12-11 13:05:34

问题


I'm trying to parse the following BPMN 2 XML with $.parseXML:

<?xml version="1.0" encoding="UTF-8"?>
<definitions id="Definition"
         xmlns:tns="http://www.jboss.org/drools">
    <process processType="Private"
         isExecutable="true"
         id="com.sample.bpmn"
         name="Sample Process"
         tns:packageName="defaultPackage" >
        <scriptTask id="_2" name="Sample Script" scriptFormat="http://www.java.com/java">
            <script>person.id</script>
        </scriptTask>
    </process>
</definitions>

but it returns with the following:

Uncaught Error: Invalid XML: 
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="Definition"
             xmlns:tns="http://www.jboss.org/drools">
    <process processType="Private"
             isExecutable="true"
             id="com.sample....<omitted>...id 

JSFiddle


EDIT

Later in the code I have to find specific parts of the XML like process, definitions etc.:

xmlDoc   = $.parseXML(data),
$xml     = $(xmlDoc),
$def     = $xml.find('definitions'),
$process = $def.find('process'),

回答1:


 var scriptBody = $('script#scriptBody').text();
 console.log(scriptBody);

 var parser = new DOMParser(); var xml =
 parser.parseFromString(scriptBody, 'text/xml'); console.log(xml);

work fine. Strange, course jquery use this implementation ( not for IE )

on debug $ function

parseXML: function( data ) {
    var xml, tmp;
    if ( !data || typeof data !== "string" ) {
        return null;
    }
    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;
    }
    if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
        jQuery.error( "Invalid XML: " + data );
    }
    return xml;
},

problems in xml.getElementsByTagName( "parsererror" )

"This page contains the following errors:error on line 2 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error."

if i remove xml declaration i get

"This page contains the following errors:error on line 10 at column 29: Extra content at the end of the document



来源:https://stackoverflow.com/questions/22401311/parsexml-cannot-parse-xml-with-script-tag-inside

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!