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

标签 javascript jquery internet-explorer-10 internet-explorer-11

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

这是我正在使用的代码,我也制作了一个 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);

最佳答案

所以,我想 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>

根子节点:

<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/

关于javascript - 如何在 IE 10/11 中可靠地将 XML 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799419/

相关文章:

javascript - 如何检查页面重新加载是否完成

javascript - 如何在 React Table 中更改 TD Click 上的 TR 样式

javascript - jQuery 单击功能不适用于 ID

css - Flex-grow 没有按预期工作( flex 元素没有我期望的宽度)

javascript - 需要解决 IE10 中的 selectSingleNode

java - Spring/Hibernate 响应中的属性为空

javascript - 为什么 React App 在网页上出现两次?

javascript - __EVENTTARGET 未定义

jquery - 使用 jQuery 更改输入值后获取值?

javascript - IE10 - 避免在 javascript 的全局范围内使用表单名称