如何在IE 10/11中可靠地将XML转换为String? [英] How to reliably convert XML to String in IE 10/11?

查看:97
本文介绍了如何在IE 10/11中可靠地将XML转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用jQuery解析XML并转换回字符串时,IE 10和IE 11未正确保留命名空间。除了编写我自己的字符串代码之外,还有另一种可以在IE 10/11中执行此操作的方法吗?

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?

这是我正在使用的代码,我也是做了一个小提琴: http://jsfiddle.net/kd2tvb4v/2/

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);


推荐答案

所以,我认为
xml [0] .outerHTML 可以完成这项工作。奇怪的是,这在FF中可以正常工作,但 xml [0] .outerHTML xml [0] .innerHTML 在IE中都是 undefined 。很奇怪!

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!

获得 outerHTML 的经典技巧在它不可用时似乎仍然适用于这种情况:追加节点到虚拟元素并使用 .html()。这似乎重新排列了属性的排序(它按字母顺序排列),但一切都被保留了:

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:

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

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);

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

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/

这篇关于如何在IE 10/11中可靠地将XML转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆