xpath与nodejs解析xml

测试xpath的工具

http://www.freeformatter.com/xpath-tester.html#ad-output

http://www.xpathtester.com/test

教程

http://www.w3school.com.cn/xpath/xpath_syntax.asp

解析xml可以安装这个包 https://github.com/yaronn/xpath.js 支持xpath。使用方法大致如下:

首先安装这个包

npm install xpath.js

再安装下面这个

npm install xmldom

然后就可以使用牛逼的xpath查找xml了

    var select = require('xpath.js') , dom = require('xmldom').DOMParser var xml = "<book><title>Harry Potter</title></book>" var doc = new dom().parseFromString(xml) var nodes = select(doc, "//title") console.log(nodes[0].localName + ": " + nodes[0].firstChild.data) console.log("node: " + nodes[0].toString())

xpath基本用法通过几个实例即可掌握

这里有一段xml

<root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org"> <actors> <actor id="1">Christian Bale</actor> <actor id="2">Liam Neeson</actor> <actor id="3">Michael Caine</actor> </actors> <foo:singers> <foo:singer id="4">Tom Waits</foo:singer> <foo:singer id="5">B.B. King</foo:singer> <foo:singer id="6">Ray Charles</foo:singer> </foo:singers> </root>
1. 选择文档节点

/


2. 选择root节点

/root


3. 选择所有是actors节点的子节点的actor节点

/root/actors/actor


4. 选择所有singer节点,不管他们在文档的什么地方

//foo:singer


5. 选择所有singer元素的id节点,不管他们在文档的什么地方

//foo:singer/@id


6. 选择第一个actor节点的文本

//actor[1]/text()


7. 选择最后一个actor节点

//actor[last()]


8. 选择第一个和第二个actor节点

//actor[position() < 3]


9. 选择所有带有id属性的actor节点

//actor[@id]


10. 选择所有id属性为3的actor节点

//actor[@id=’3′]


11. 选择所有id属性小于3的actor节点

//actor[@id<=3]


12. 选择所有singers节点的子节点

/root/foo:singers/*


13. 选择文档中所有节点

//*


14. 选择所有actor节点与singer节点

//actor|//foo:singer


15. 得到文档中第一个节点的节点名

name(//*[1])


16.得到第一个actor节点的id属性的数量

number(//actor[1]/@id)


17. 得到第一个actor节点的id属性的字符串表示

string(//actor[1]/@id)


18. 得到第一个actor节点内文本的长度

string-length(//actor[1]/text())


19. Select the local name of the first ‘singer’ element, i.e. without the namespace.

local-name(//foo:singer[1])


20. 计算singer节点的数量

count(//foo:singer)


21. Select the sum of the ‘id’ attributes of the ‘singer’ elements.

sum(//foo:singer/@id)

 

 

 

from:http://ju.outofmemory.cn/entry/73154

转载于:https://www.cnblogs.com/c-x-a/p/5481269.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值