Home > Back-end >  xml.etree get tag which has a child with specific attribute
xml.etree get tag which has a child with specific attribute

Time:06-17

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?

CodePudding user response:

Here your solution, you can check element with sub-element inside "//parent[./direct_child]" or "//parent[.//children_of_child]" result element will be the parent

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

CodePudding user response:

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'}
  • Related