简体   繁体   中英

xml.etree get tag which has a child with specific attribute

I have the following xml file:

<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>

I want to select the <node> tag which contains a <tag> tag with attribute v="traffic_signals" .
However if I use the following code, I get the <tag> tag in return.

root.find('.//node/tag[@v="traffic_signals"]')

And as far as i know, xml.etree doesn't provide a way to get parent.

How can I actually get the node tag?

Not very eficcient - but it works

import xml.etree.ElementTree as ET

xml = '''<r>
<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>
</r>'''

root = ET.fromstring(xml)
node = [n for n in root.findall('.node') if n.find('tag[@v="traffic_signals"]') is not None][0]
print(node.attrib)

output

{'id': '1416646245'}

在这里您的解决方案,您可以检查“//parent[./direct_child]”或“//parent[.//children_of_child]”结果元素中包含子元素的元素将是父元素

root.find('.//node[./tag[@v="traffic_signals"]]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM