本文继续沿用第三章的 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>]

最新文章

  1. 《爵迹》侵权链接多为个人用户分享到个人网盘 总结说明:推广途径为 网盘&gt;微博&gt;博客&gt;贴吧&gt;知道
  2. RecyclerView的基本创建
  3. 新建数据库,然后使用SQL语句创建表、存储过程、用户说明
  4. SQLite学习第03天:环境搭建
  5. Ajax请求安全性讨论 - Eric.Chen(转)
  6. NDK 的helloworld步奏
  7. Android应用开发实例篇(1)-----简易涂鸦板
  8. EF的四种开发模式
  9. 可以随鼠标拖拽的div
  10. 记MVC学习过程中一次传参到View时遇到的错误
  11. 《Office 365开发入门指南教程》正式上线,限时优惠和邀请分享推广
  12. java中线程安全的map是ConcurrentHashMap
  13. 使用Python编写简单的端口扫描器的实例分享【转】
  14. Ubuntu14.04 libboost_program_options.so.1.54.0: cannot open shared object file: No such file or directory
  15. 山寨&quot;每日故宫&quot;应用的图层遮罩效果
  16. soj1763.传球游戏
  17. Linux Shell管道调用用户定义函数(使shell支持map函数式特性)
  18. 匿名方法,lambad表达式,匿名类
  19. 【转载】使用SoapUI 测试Web Service
  20. P2341 [HAOI2006]受欢迎的牛(tarjan+缩点)

热门文章

  1. [Qt] 利用QtWebKit完成JavaScript访问C++对象
  2. Ubuntu中基于QT的系统网线连接状态的实时监视
  3. ssh 中 远程文件传输
  4. 在C++中调用DLL中的函数(2)
  5. 【Html】div 加载 html页面的方法
  6. 第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作、增、删、改、查
  7. ZBar与ZXing使用后感觉
  8. e808. 建立菜单栏,菜单,菜单项
  9. 理解并实现PubSub模式
  10. Python——hmac