nodejs實現解析xml字串為對象的方法樣本,nodejsxml

來源:互聯網
上載者:User

nodejs實現解析xml字串為對象的方法樣本,nodejsxml

本文執行個體講述了nodejs實現解析xml字串為對象的方法。分享給大家供大家參考,具體如下:

var xmlreader = require("xmlreader");var fs = require("fs");var xml_string = '<response id="1" shop="aldi">'      +    'This is some other content'      +    '<who name="james">James May</who>'      +    '<who name="sam">'      +      'Sam Decrock'      +      '<location>Belgium</location>'      +    '</who>'      +    '<who name="jack">Jack Johnsen</who>'      +    '<games age="6">'      +      '<game>Some great game</game>'      +      '<game>Some other great game</game>'      +    '</games>'      +    '<note>These are some notes</note>'      +  '</response>';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:擷取節點內的文本,僅當前節點的文本,不包含子節點的文本。

PS:這裡再為大家提供幾款關於xml操作的線上工具供大家參考使用:

線上XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson

線上格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat

XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代碼線上格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

希望本文所述對大家nodejs程式設計有所協助。

聯繫我們

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