js實現xml轉化成字串

來源:互聯網
上載者:User

標籤:style   io   ar   os   sp   for   檔案   on   問題   

 xml字串轉xml dom
經常遇到在js裡面需要解析xml的問題,然而有時候,後台返回的不是dom 而是string 字串,需要將字串轉換成dom對象,然後才可以進行節點值解析和讀取

function createXml(str)
{
  if(document.all)
      {
        var xmlDom=new ActiveXObject("Microsoft.XMLDOM")
        xmlDom.loadXML(str)
        return xmlDom
  }
  else
      {
         return new DOMParser().parseFromString(str, "text/xml")
  }

如果在js端是讀取檔案,那就更方便了
       var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
  xmlDoc.async = false;
  xmlDoc.load("檔案路徑");
2. xml dom轉xml字串
function xmlToString(xmlObj)
{
    if(document.all) //IE瀏覽器
    {
        return xmlObj.xml;
    }
    else //其他瀏覽器
    {
        return (new XMLSerializer()).serializeToString(xmlObj);
    }
}
3. 載入xml檔案
function loadXML()
{
        try //Internet Explorer
       {
          xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
       }
        catch(e)
       {
          try //Firefox, Mozilla, Opera, etc.
        {
            xmlDoc=document.implementation.createDocument("","",null);
        }
      catch(e)
      {
          alert(e.message)}
      }
        try
      {
          xmlDoc.async=false;
          xmlDoc.load("/example/xdom/books.xml");
          document.write("xmlDoc is loaded, ready for use");
      }
        catch(e)
        {
            alert(e.message)
        }
}

js實現xml轉化成字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.