首頁 > web前端 > js教程 > 主體

nodejs解析xml字串為物件的實例

小云云
發布: 2018-03-16 09:04:43
原創
2335 人瀏覽過

本文主要和大家介紹了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:取得節點內的文本,僅當前節點的文本,不包含子節點的文本。

相關推薦:

php解析xml並產生sql語句的實作方法

PHP解析xml格式資料工具類實例分享

解析XML的四個方法

#

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

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!