问题
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