在 Python 中搜索 XML 内容 [英] Search XML content in Python

查看:25
本文介绍了在 Python 中搜索 XML 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 XML 文件:

I have the following XML file:

借助 StackOverflow 的一些帮助,我设法实现了我计划做的一些事情.现在,我想在我的脚本中添加一个搜索功能并单独处理该子树.比如我问用户——什么ID?他输入AL2012-2015-088.在一个巨大的 XML 文件中递归搜索这个 ID,脚本应该找到这个 ID 并打印它的元素.

With some help of StackOverflow, I managed to achieve some of what I planned to do. Now, I want to add a search function to my script and singularly work on that sub-tree. For example, I ask the user - what ID? He enters AL2012-2015-088. Recursively searching for this ID in a huge XML file, the script should find this ID and print the elements it has.

我使用了 content.find("AL2012-2015-088"),但它不起作用!

I used content.find("AL2012-2015-088"), but it won't work!

推荐答案

如果您要切换到 lxml.etree,您将能够使用 XPath 表达式的全部功能(您还可以显着加快速度).

If you would switch to lxml.etree, you would be able to use the full power of XPath expressions (you would also speed things up dramatically).

这是一个示例 - 使用所需的 id 定位 update 元素并打印出 title:

Here is an example - locating the update element with a desired id and printing out the title:

from lxml import etree as ET

id_that_user_enters = "AL2012-2015-088"
tree = ET.parse("example.xml")

update = tree.xpath("//update[id = '%s']" % id_that_user_enters)[0]
print(update.findtext("title"))

打印:

Amazon Linux 2012.03 - AL2012-2015-088: medium priority package update for gnutls

这篇关于在 Python 中搜索 XML 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆