nodejs解析xml字符串为对象

  1. var xmlreader = require("xmlreader");  
  2. var fs = require("fs");  
  3.   
  4. var xml_string = '<response id="1" shop="aldi">'  
  5.             +       'This is some other content'  
  6.             +       '<who name="james">James May</who>'  
  7.             +       '<who name="sam">'  
  8.             +           'Sam Decrock'  
  9.             +           '<location>Belgium</location>'  
  10.             +       '</who>'  
  11.             +       '<who name="jack">Jack Johnsen</who>'  
  12.             +       '<games age="6">'  
  13.             +           '<game>Some great game</game>'  
  14.             +           '<game>Some other great game</game>'  
  15.             +       '</games>'  
  16.             +       '<note>These are some notes</note>'  
  17.             +   '</response>';  
  18.   
  19.   
  20. xmlreader.read(xml_string, function(errors, response){  
  21.     if(null !== errors ){  
  22.         console.log(errors)  
  23.         return;  
  24.     }  
  25.     console.log( response.response );  
  26.     console.log( response.response.text() );  
  27. });  

没啥新奇的,看看输出吧

第一句输出结果为:

[javascript]  view plain  copy
  1. {  
  2.     attributes : [Function],  
  3.     parent : [Function],  
  4.     count : [Function],  
  5.     at : [Function],  
  6.     each : [Function],  
  7.     text : [Function],  
  8.     who : {  
  9.         array : [[Object], [Object], [Object]],  
  10.         count : [Function],  
  11.         at : [Function],  
  12.         each : [Function]  
  13.     },  
  14.     games : {  
  15.         attributes : [Function],  
  16.         parent : [Function],  
  17.         count : [Function],  
  18.         at : [Function],  
  19.         each : [Function],  
  20.         game : {  
  21.             array : [Object],  
  22.             count : [Function],  
  23.             at : [Function],  
  24.             each : [Function]  
  25.         }  
  26.     },  
  27.     note : {  
  28.         attributes : [Function],  
  29.         parent : [Function],  
  30.         count : [Function],  
  31.         at : [Function],  
  32.         each : [Function],  
  33.         text : [Function]  
  34.     }  
  35. }  

第二句输出:

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:获取节点内的文本,仅当前节点的文本,不包含子节点的文本。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值