我的parsexml代码:
var parseXml = function (xml) {
var dom = null;
if (window.DOMParser) {
try {
dom = (new DOMParser()).parseFromString(xml, "text/xml");
}
catch (e) { dom = null; }
}
else if (window.ActiveXObject) {
try {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) // parse error ..
window.alert(dom.parseError.reason + dom.parseError.srcText);
}
catch (e) { dom = null; }
}
else
alert("cannot parse xml string!");
return dom;
}
现在假设
s="<a>random</a>";
b=parseXml(s);
现在我想从s
返回b
。我该怎么做?
答案 0 :(得分:3)
在大多数浏览器中需要XMLSerializer
,在旧版IE中需要XML节点的xml
属性:
function serializeXmlNode(xmlNode) {
if (typeof window.XMLSerializer != "undefined") {
return new window.XMLSerializer().serializeToString(xmlNode);
} else if (typeof xmlNode.xml != "undefined") {
return xmlNode.xml;
}
return "";
}
var xmlStr = serializeXmlNode(b);
答案 1 :(得分:0)
您需要一个XMLSerializer
(MDN docu)对象来将XML树转换回字符串:
var ser = new XMLSerializer();
s = ser.serializeToString( b );