国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

nodejs實現解析xml字符串為對象的方法示例

2024-05-06 16:43:05
字體:
來源:轉載
供稿:網友

本文實例講述了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:獲取節點內的文本,僅當前節點的文本,不包含子節點的文本。

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


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宝鸡市| 沭阳县| 阿合奇县| 澄江县| 平果县| 沭阳县| 祁门县| 乐都县| 安图县| 南康市| 新蔡县| 招远市| 遂昌县| 普兰店市| 永登县| 海南省| 垦利县| 西盟| 崇州市| 吉林省| 古田县| 景宁| 米易县| 德江县| 根河市| 如东县| 南靖县| 于都县| 黄山市| 威宁| 南溪县| 简阳市| 安溪县| 怀仁县| 东丽区| 安乡县| 吴旗县| 女性| 宁城县| 泰顺县| 吴川市|