zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    JSP/Servlet相关
    mysql 相关问题解决
    Git常用
    利用JDBC连接MySQL并使用MySQL
    memcache、redis原理对比
    Python 2.7.x 和 3.x 版本的重要区别
    python 单例模式
    python 装饰器原理及用法
    python 冒泡排序
    python 迭代器和生成器
  • 原文地址:https://www.cnblogs.com/c-x-a/p/5481269.html
Copyright © 2011-2022 走看看