Find parent element of a 'title' xml tag containing specific text using Python ElementTree

為{幸葍}努か 提交于 2019-12-20 06:22:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!