Ali Karaca
Ali Karaca

Reputation: 3851

python find tags in deep nodes xml

I want to reach the "thirdDepth1" tag using python ElementTree library. Below is the simplified version. In my real xml its depth is dynamic. So can't reach it with giving path, using find(),findall(), iterfind(). Any ideas?

<root>
    <firstDepth1>
        <secondDepth1>
            <thirdDepth1>thirdDepthVal</thirdDepth1>
        </secondDepth1>
    </firstDepth1>
    <firstDepth2>
        <secondDepth2></secondDepth2>
    </firstDepth2>
</root>

Upvotes: 1

Views: 2178

Answers (1)

Ali Karaca
Ali Karaca

Reputation: 3851

import xml.etree.ElementTree as ET

tree = ET.parse("testxmlreqpython.xml")

root = tree.getroot()

element = root.find(".//thirdDepth1")

print(element)

From @Luis Muñoz comment, this can be achived by using xpath as ".//thirdDepth1"

Upvotes: 1

Related Questions