Search XML content in Python

一曲冷凌霜 提交于 2020-01-03 03:29:53

问题


I have the following XML file:

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.

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


回答1:


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).

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"))

Prints:

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



回答2:


I believe the find command is designed to find tags as opposed to the text within the tags so you should do find on id. I'm not sure which info you need from the XML, but here is an example that gets the title.

import xml.etree.ElementTree as elt
content = elt.parse('example.xml').getroot()

def get_id_info(inputID):
    for child in content:
        if child.find('id').text == inputID:
            print child.find('title').text

get_id_info('AL2012-2014-001')

gives Amazon Linux 2012.03 - AL2012-2014-001...



来源:https://stackoverflow.com/questions/36901802/search-xml-content-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!