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

亡梦爱人 提交于 2019-12-07 17:58:33

问题


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/



来源:https://stackoverflow.com/questions/28799419/how-to-reliably-convert-xml-to-string-in-ie-10-11

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