问题
I wish to parse an xml file and extract the parent <sec>
which contains a <title>
matching a specific text using Python 3.7 & ElementTree
...
<sec id="s0010">
<label>2</label>
<title>Materials and methods</title>
</sec>
<sec id="s0015">
<label>3</label>
<title>Summary</title>
</sec>
...
I was able to locate the title using ET:
for title in parent.iter('title'):
text = title.text
if(text):
if("methods" in text.lower()):
print("**title: "+text+"****")
But how do I get the parent object (<sec>
) of the title containing the text of interest?
回答1:
Do a (nested) iteration in 2 steps: on sec and then on title. Something like:
for sec in parent.iter("sec"):
for title in sec.iter("title"):
text = title.text
if text and "methods" in text.lower():
print("**title: " + text + " **** sec id: " + sec.get("id", ""))
For more details, check [Python 3]: xml.etree.ElementTree - The ElementTree XML API.
来源:https://stackoverflow.com/questions/54518163/find-parent-element-of-a-title-xml-tag-containing-specific-text-using-python-e