首頁  >  文章  >  web前端  >  nodejs實作解析xml字串為物件的方法範例

nodejs實作解析xml字串為物件的方法範例

亚连
亚连原創
2018-05-30 10:56:371560瀏覽

這篇文章主要介紹了nodejs實作解析xml字串為物件的方法,涉及nodejs針對xml格式字串的解析與轉換相關操作技巧,需要的朋友可以參考下

本文實例講述了nodejs實作解析xml字串為物件的方法。分享給大家供大家參考,具體如下:

var xmlreader = require("xmlreader");
var fs = require("fs");
var xml_string = &#39;<response id="1" shop="aldi">&#39;
      +    &#39;This is some other content&#39;
      +    &#39;<who name="james">James May</who>&#39;
      +    &#39;<who name="sam">&#39;
      +      &#39;Sam Decrock&#39;
      +      &#39;<location>Belgium</location>&#39;
      +    &#39;</who>&#39;
      +    &#39;<who name="jack">Jack Johnsen</who>&#39;
      +    &#39;<games age="6">&#39;
      +      &#39;<game>Some great game</game>&#39;
      +      &#39;<game>Some other great game</game>&#39;
      +    &#39;</games>&#39;
      +    &#39;<note>These are some notes</note>&#39;
      +  &#39;</response>&#39;;
xmlreader.read(xml_string, function(errors, response){
  if(null !== errors ){
    console.log(errors)
    return;
  }
  console.log( response.response );
  console.log( response.response.text() );
});

#沒啥新奇的,看看輸出吧

第一句輸出結果為:

{
  attributes : [Function],
  parent : [Function],
  count : [Function],
  at : [Function],
  each : [Function],
  text : [Function],
  who : {
    array : [[Object], [Object], [Object]],
    count : [Function],
    at : [Function],
    each : [Function]
  },
  games : {
    attributes : [Function],
    parent : [Function],
    count : [Function],
    at : [Function],
    each : [Function],
    game : {
      array : [Object],
      count : [Function],
      at : [Function],
      each : [Function]
    }
  },
  note : {
    attributes : [Function],
    parent : [Function],
    count : [Function],
    at : [Function],
    each : [Function],
    text : [Function]
  }
}

第二句輸出:

This is some other content

根據輸出我們可以猜這東西是怎麼回事了。

1、xmlreader將xml轉換為JSON物件(這樣表述不準確,但是大家知道怎麼一回事)。
2、轉換成的JSON物件的巢狀結構與原xml標籤巢狀結構相同。
3、視xml中同一層級出現某標籤次數不同(一次和多次)生出不同的對應對象,如上的node為一次,who為三次。
4、提供了一下函數供操作屬性或是遍歷等等。

各方法意義:

1、attributes:取得所有屬性。
2、parent:取得父節點。
3、count:取得數目。
4、at:取得下標為指定值的節點。
5、each:遍歷,參數為一個函數。
6、text:取得節點內的文本,僅當前節點的文本,不包含子節點的文本。

上面是我整理給大家的,希望今後對大家有幫助。

相關文章:

Angular使用操作事件指令ng-click傳遞多個參數範例

JavaScript程式碼實作txt檔案的上傳預覽功能

Angularjs實作控制器之間通訊方式實例總結

##

以上是nodejs實作解析xml字串為物件的方法範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn