[XPath] XPath 与 lxml (五)XPath 实例

本文继续沿用第三章的 XML 示例文档。

 

选取价格高于30的 price 节点

# 从父节点进行筛选
>>> root.xpath('//book[price>30]/price')
[<Element price at 0x2d888c8>]

# 直接对 price 进行筛选
>>> root.xpath('//price[text()>30]')
[<Element price at 0x2d888c8>]

 

选取 price 高于 30 的 title 节点

# 从父节点开始选取
>>> root.xpath('//book[price>30]/title')
[<Element title at 0x2d88878>]

# 从节点本身选取
>>> root.xpath('//price[text()>30]//preceding-sibling::title|following-sibling::title')
[<Element title at 0x2d88878>]

# 从 price 到父节点选取
>>> root.xpath('//price[text()>30]//parent::*/title')
[<Element title at 0x2d88878>]

 

处理命名空间

>>> xml = """<?xml version="1.0" encoding="utf8"?>
<bookstore xmlns:a="http://www.google.com">
    <a:book>
        <title lang="eng">Harry Potter</title>
        <price>29.99</price>
    </a:book>
    <book>
        <title lang="eng">Learning XML</title>
        <price>39.95</price>
    </book>
</bookstore>"""

# 获取根节点
>>> root = etree.fromstring(xml)

# 选取不带命名空间的 book 元素
>>> root.xpath('//book')
[<Element book at 0x2d88940>]

# 选取所有的 book 元素,无论是否含有命名空间
# 其中 namespace 参数为一个字典对象,映射了命名空间前缀,本例中直接使用了文档原有的命名空间与前缀。
>>> root.xpath('//a:book|//book', namespaces=root.nsmap)
[<Element {http://www.google.com}book at 0x2d88878>, <Element book at 0x2d88940>]
posted @ 2014-07-28 00:09  iFantasticMe  阅读(1495)  评论(0编辑  收藏  举报