如何在IE 10/11中可靠地将XML转换为字符串

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

本文关键字:XML 转换 字符串 IE      更新时间:2023-09-26

在使用jQuery解析XML并转换回字符串时,IE 10和IE 11没有正确保留命名空间。除了编写我自己的字符串化代码之外,在IE 10/11中还有其他公认的方法吗?

这是我正在使用的代码,我也做了一个小提琴: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);
所以

,我想 xml[0].outerHTML会做这项工作。奇怪的是,这在FF中按预期工作,但xml[0].outerHTMLxml[0].innerHTML在IE中都undefined。奇怪!

在这种情况下,当outerHTML不可用时获取的经典技巧似乎仍然有效:将节点附加到虚拟元素并使用 .html() .这似乎重新排列了属性的顺序(按字母顺序排列(,但所有内容都保留了:

在IE11中测试,没有IE10方便:

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

原始 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>

小提琴:http://jsfiddle.net/kd2tvb4v/4/