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

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

nodejs實(shí)現(xiàn)解析xml字符串為對(duì)象的方法示例

2024-05-06 15:20:40
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了nodejs實(shí)現(xiàn)解析xml字符串為對(duì)象的方法。分享給大家供大家參考,具體如下:

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() );});

沒(méi)啥新奇的,看看輸出吧

第一句輸出結(jié)果為:

{  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

根據(jù)輸出我們就可以猜這東西是怎么回事兒了。

1、xmlreader將xml轉(zhuǎn)換為JSON對(duì)象(這樣表述不準(zhǔn)確,但是大家知道怎么一回事兒)。
2、轉(zhuǎn)換成的JSON對(duì)象的嵌套結(jié)構(gòu)與原xml標(biāo)簽嵌套結(jié)構(gòu)相同。
3、視xml中同一級(jí)別出現(xiàn)某標(biāo)簽次數(shù)不同(一次和多次)生出不同的對(duì)應(yīng)對(duì)象,如上的node為一次,who為三次。
4、提供了一下函數(shù)供操作屬性或者遍歷等等。

各方法含義:

1、attributes:獲取所有屬性。
2、parent:獲取父節(jié)點(diǎn)。
3、count:獲取數(shù)目。
4、at:獲取下標(biāo)為指定值的節(jié)點(diǎn)。
5、each:遍歷,參數(shù)為一個(gè)函數(shù)。
6、text:獲取節(jié)點(diǎn)內(nèi)的文本,僅當(dāng)前節(jié)點(diǎn)的文本,不包含子節(jié)點(diǎn)的文本。

PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.Vevb.com/code/xmljson

在線格式化XML/在線壓縮XML:
http://tools.Vevb.com/code/xmlformat

XML在線壓縮/格式化工具:

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 阳高县| 邻水| 樟树市| 阿拉善盟| 仪陇县| 望江县| 天长市| 和政县| 远安县| 通州市| 巨鹿县| 防城港市| 河南省| 莆田市| 光山县| 漠河县| 永嘉县| 孟州市| 蓬莱市| 清徐县| 湖口县| 页游| 屯留县| 淄博市| 甘孜县| 旅游| 绵阳市| 阿坝县| 岢岚县| 乳源| 炎陵县| 潼关县| 新化县| 广南县| 合川市| 西乌珠穆沁旗| 泸西县| 牙克石市| 武隆县| 宁夏| 五原县|