python - 使用 Python ElementTree 查找包含特定文本的“标题”xml 标记的父元素
问题描述
我希望解析一个 xml 文件并使用 Python 3.7 和 ElementTree 提取<sec>
包含<title>
匹配特定文本的父级
...
<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 - The ElementTree XML API。
推荐阅读
- c# - 试图避免在表中重复插入值
- excel - 将公式从 excel 更改为 vba,但出现预期错误:)
- c# - 基于从日期和到日期选择和 ipno、prno 选择的患者详细信息
- database - 如何使用flyway将数据从一个数据库迁移到另一个数据库?
- java - Java 持久性:要列出的 @ManyToMany 项目
- date - 需要在 Power BI 中设置上个月的月底
- javascript - 如何对齐资源列和事件列的行高?
- mysql - 如何使用 CodeIgniter 在数据库中插入多个值?
- c++ - 我想同步等待 IP 地址更改
- android - Glide 仅在某些设备上返回位图