JS解析XML

來源:互聯網
上載者:User
朋友很急,正好我沒什麼事就一起幫忙,順便學一學。
前一段還以為js上解析xml是ajax的功勞,其實不然。
朋友的問題如下:
Dear Applicant,
Thank you very much for your interest in this position. Would you please send me some _fragment_ of code and designment document that you've worked on in your past projects?  That will helps us better evaluate your applicaiton.
We hope you can demonstrate your experience/learning ability by finishing the assignment below. It'll be a jscript function to transform a given format of XML input to another XML format.
The input would be like:

<?xml version="1.0"?>
<menu xmlns="">
    <menuitem>
        <node>1</node>
        <parent>1</parent>
        <name>parent</name>
    </menuitem>
    <menuitem>
        <node>2</node>
        <parent>1</parent>
        <name>1st child</name>
    </menuitem>
    <menuitem>
        <node>3</node>
        <parent>1</parent>
        <name>2nd child</name>
    </menuitem>
    <menuitem>
        <node>4</node>
        <parent>2</parent>
        <name>grantchild</name>
    </menuitem>
</menu>

The output would be like:
<?xml version="1.0"?>
<menu xmlns="">
    <menuitem>
        <name>parent</name>
        <menuitem>
            <name>1st child</name>
            <menuitem>
                <name>grand child</name>
            </menuitem>
        </menuitem>
        <menuitem>
            <name>2nd child</name>
        </menuitem>
    </menuitem>
</menu>
In the input format, tag "node" and "parent" specifies the structure of the tree, while "name" and others tags should be copied to the output format.  Therefore, the code should be able to handle the following fragment of XML:
<menuitem>
        <node>2</node>
        <parent>1</parent>
        <name>1st child</name>
        <lastName>Dai</lastName>
        <firstName>Kun</firstName>
</menuitem>
Thank you again for your time, and please reply this email after you get it.
我只幫忙解析,後面嗎,只提供思路:解析的元素封裝成js的object,之後處理邏輯就和java一樣了。
解析代碼:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function loadXml(){
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
     //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)}
        //   }
   xmlDoc.async="false";//取消非同步載入
   xmlDoc.load("a.xml");
   //xmlDoc.loadXmlString(字串);如果xml的內容是一個字串比如<x>1</x>可以用此方法
   //var items = xmlDoc.selectNodes("/menu/menuitem");
   //alert(items.length);
  // for(var i=0;i<items.length;i++){
  // alert(xmlDoc.selectSingleNode("/menu/menuitem["+i+"]/node").text);
  // alert(xmlDoc.selectSingleNode("/menu/menuitem["+i+"]/parent").text);
  // alert(xmlDoc.selectSingleNode("/menu/menuitem["+i+"]/name").text);
   //}
  //方法2
  var items = xmlDoc.getElementsByTagName("menuitem");
   alert(items.length);
   for(var i=0;i<items.length;i++){
   var x = items.firstChild;
   alert(x.getAttribute("title"));//取得標籤上的屬性,如<x title="a"></x>取得title的值'a'
   alert(x.text);//或者xmldoc.getElementsByTagName("node").text
   alert(x.nextSibling.text);//nextSibling方法是取得下一個node
   alert(x.nextSibling.nextSibling.text);
   }
  }
  function getNode(doc, xpath) {
  varretval = "";
  var value = doc.selectSingleNode(xpath);
  if (value) retval = value.text;
  return retval;
    }
//-->
</SCRIPT>
</HEAD>

<BODY>
<input type="button" onclick="loadXml()" value = "ok">
</BODY>
</HTML>
用了兩種方法,第一種是通過網上google的例子依賴於selectSingleNode和selectNodes方法,
個人覺得通用性很難實現,如果實現的話,需要的是封裝路徑,而且事先要知道整個xml檔案的完整結構。
第二種方法,是我從w3school上學到的,在被xmlDoc載入之後,xml部分應該就具備了頁面元素的特性,所以通過getElementsXX等方法就可以去做,在w3school上學到的竅門,拿到firstChild之後後面的元素就用nextsibling,當然需要加判斷的,測試的關係沒有加。
這次發現,對與html沒有足夠充分的瞭解而去研究js架構是比較困難的,所以w3school繼續學習中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.