How to reliably convert XML to String in IE 10/11?

2019-05-11 23:07发布

问题:

Namespaces are not being properly preserved by IE 10 and IE 11 when parsing XML with jQuery and converting back to string. Is there another accepted means of doing this in IE 10/11, aside from writing my own stringify code?

Here is the code I am using, which I've also made a fiddle: http://jsfiddle.net/kd2tvb4v/2/

var origXml = 
    '<styleSheet' 
        + ' xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"'
        + ' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"'
        + ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
        + ' mc:Ignorable="x14ac">'
            + '<fonts count="0" x14ac:knownFonts="1"></fonts>'
        + '</styleSheet>';
var xml = $($.parseXML(origXml).documentElement);
var reprocessedXml = (new XMLSerializer()).serializeToString(xml[0]);

$('#origXml').text(origXml);
$('#reprocessedXml').text(reprocessedXml);

回答1:

So, I thought xml[0].outerHTML would do the job. Oddly enough, this works as expected in FF, but xml[0].outerHTML and xml[0].innerHTML are both undefined in IE. Weird!

The classic trick for getting outerHTML when it is not available still seems to work in this case: Append the node to a dummy element and use .html(). This seems to rearrange the ordering of attributes (it alphabetizes them), but everything is preserved:

Tested in IE11, don't have IE10 handy:

//...your original code...
var xml = $($.parseXML(origXml).documentElement);
var rootChildXml=$('<root />').append(xml).html();
console.log(origXML,rootChildXml);

Original XML:

<styleSheet xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" 
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
 mc:Ignorable="x14ac">
<fonts count="0" x14ac:knownFonts="1"></fonts></styleSheet>

rootChildXml:

<stylesheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" 
 mc:Ignorable="x14ac" 
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
<fonts x14ac:knownFonts="1" count="0"></fonts></stylesheet>

fiddle: http://jsfiddle.net/kd2tvb4v/4/