从解析的xml构造xml字符串

时间:2012-06-29 10:56:55

标签: javascript xml-parsing

我的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。我该怎么做?

2 个答案:

答案 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)

您需要一个XMLSerializerMDN docu)对象来将XML树转换回字符串:

var ser = new XMLSerializer(); 
s = ser.serializeToString( b );