使用Python ElementTree查找包含特定文本的“标题” xml标记的父元素 [英] Find parent element of a 'title' xml tag containing specific text using Python ElementTree
本文介绍了使用Python ElementTree查找包含特定文本的“标题” xml标记的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想解析一个xml文件并提取包含< title>
< sec> >使用Python 3.7&匹配特定文本ElementTree
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>
...
我能够使用ET查找标题:
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+"****")
但是我如何获得该对象的父对象(< sec>
)标题是否包含感兴趣的文本?
But how do I get the parent object (<sec>
) of the title containing the text of interest?
推荐答案
执行(嵌套)迭代需要2个步骤: sec ,然后点击标题。像这样的东西:
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", ""))
有关更多详细信息,请检查 [Python 3.Docs]:xml.etree.ElementTree-ElementTree XML API 。
For more details, check [Python 3.Docs]: xml.etree.ElementTree - The ElementTree XML API.
这篇关于使用Python ElementTree查找包含特定文本的“标题” xml标记的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文