[英]Find parent element of a 'title' xml tag containing specific text using Python ElementTree
我希望解析一个 xml 文件并使用 Python 3.7 和 ElementTree 提取包含与特定文本匹配的<title>
的父<sec>
...
<sec id="s0010">
<label>2</label>
<title>Materials and methods</title>
</sec>
<sec id="s0015">
<label>3</label>
<title>Summary</title>
</sec>
...
我能够使用 ET 找到标题:
for title in parent.iter('title'):
text = title.text
if(text):
if("methods" in text.lower()):
print("**title: "+text+"****")
但是如何获取包含感兴趣文本的标题的父对象 ( <sec>
)?
分两步进行(嵌套)迭代:在sec 上,然后在title 上。 就像是:
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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.