lee
lee

Reputation: 47

Getting the "sibling" of a "child" in xml.etree.ElementTree, Python,

I am new to XML and python, I am struggling to get the "sibling" of a "child"

I have this XML

<notes>
    <Def id="1"> 
        <module>DDAC</module>
        <tags> lalala</tags>
        <description> John and Mark are good friends. </description>
    </Def>
    <Def id="2"> 
        <module>FYP</module>
        <tags> lelele</tags>
        <description> John works in Google. </description>
    </Def>
    <Def id="3"> 
        <module>FYP</module>
        <tags> lilili</tags>
        <description> Mark work in IBM. </description>
    </Def>
    <Def id="4"> 
        <module>DDAC</module>
        <tags> lololo</tags>
        <description> A computer can help you do stuff </description>
    </Def>
    <Def id="5"> 
        <module>IMNPD</module>
        <tags> lululu</tags>
        <description> The internet is a world wide web </description>
    </Def>
</notes>

I want to get the description for all the module "DDAC"

for g in root.iter('module'):
    if g.text == 'DDAC':
        x = root.iter("description")
        print(x)

my desire output is:

John and Mark are good friends.

A computer can help you do stuff

but I am getting the object not the text

Upvotes: 2

Views: 4820

Answers (1)

haraprasadj
haraprasadj

Reputation: 1087

Assuming your xml data is in a file called test.xml, the following code should work:

import xml.etree.ElementTree as ET

root = ET.parse('test.xml').getroot()
for Def in root.findall('Def'):
    module = Def.find('module').text
    if module == 'DDAC':
        print(Def.find('description').text)

Upvotes: 3

Related Questions