首页 > 解决方案 > 使用 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>包含感兴趣文本的标题的父对象 ( )?

标签: pythonxmlelementtree

解决方案


分两步进行(嵌套)迭代:在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


推荐阅读