Vincent
Vincent

Reputation: 113

XML file parsing - Get data from a child of a child

I know how to get data from a child tag but I would like to get data from a child tag of a child tag of the "root" tag. We can use this database for example :

<DB>
    <Entry>
        <Name></Name>
        <DisplayName>Assembly.iam</DisplayName>
        <Scalar>
          <Name>d0</Name>
          <DisplayName>d0 (value = 0 mm)</DisplayName>
          <Value>0</Value>
        </Scalar>
    </Entry>
</DB>

Here is my code to get data from just a child tag :

from xml.etree import ElementTree

tree = ElementTree.parse("C:\\Users\\Vince\\test.xml")
root = tree.getroot()
for entry in root.findall('Entry'):
    name = entry.find('DisplayName').text
    print(name)

It outputs : Assembly.iam

But now, how can I display d0 (value = 0 mm) ?

Upvotes: 1

Views: 86

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90859

For printing all display names , You should try -

dnames = entry.findall(".//DisplayName")
for x in dnames:
    print(x.text)

For getting the specific display name under <Scalar> , you can do the below-

name = entry.find('./Scalar/DisplayName').text
print(name)

Upvotes: 2

Related Questions