xpath与nodejs解析xml
2016-05-11 11:26
218 查看
测试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
相关文章推荐
- nodejs xpath
- Jenkins Slave Nodes – using the Swarm Plugin
- HADOOP 启动NodeManager闪退,logs信息:java.net.NoRouteToHostException: 没有到主机的路由
- [NodeJS]Jenkins-cli
- Hadoop2源码分析-HDFS datanode核心模块分析
- Node.js机制及原理理解初步
- LeetCode 025 Reverse Nodes in k-Group
- 树——populating-next-right-pointers-in-each-node(层序遍历变型)
- leetcode.222. Count Complete Tree Nodes
- 第一个Node.js应用
- Node.js的安装
- 今天使用babel遇到的一个错误
- 云监控中inode使用率监控具体作用是什么
- Nodejs 安装
- Node.js学习总纲
- hadoop关不掉namenode的解决办法
- nodejs学习之表单提交(1)
- 237DeleteNodeinaLinkedList
- 《深入浅出Node.js》学习笔记——(二)模块机制
- Leetcode - 19. Remove Nth Node from end of List