wiki wiki
wiki wiki

Reputation: 27

Parse childs in XML python

I have a XML code like:

<?xml version='1.0' encoding="UTF-8"?>
<coureurs>
<coureur>
<nom>Patrick</nom><hair>Inexistants</hair>
</coureur>


</coureurs>                                                                                  

And i want to print that:

  Patrick inexistents
      Etc...

For now my code is :
from lxml import etree
tree = etree.parse(file.xml)
for coureur in tree.xpath("/coureurs/coureur/nom"):
print(user.text)

but it returns blank, when i do: for user in tree.xpath("/coureurs/coureur/hair"): it only returns hair. what should i do?

Upvotes: 0

Views: 52

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90889

I am still not able to reproduce the issue with the xml and code you provided. But seems like you have left out a lot of xml , and most probably the XPATH may not be working for you if coureurs is not the direct root of the xml (or its direct child) .

In such cases, you can use the following XPATH to get each coureur node in the xml (that is the child of a coureurs node) -

//coureurs/coureur

This would give you all <coureur> tag elements from the xml , and then you ca iterate over that to print it's child's text . Example Code -

for user in tree.xpath('//coureurs/coureur'):
    for child in user:
        print(child.text,end=" ")
    print()

Example/Demo -

In [26]: s = """<?xml version='1.0' encoding="UTF-8"?>
   ....: <coureurs>
   ....: <coureur>
   ....: <nom>Patrick</nom><hair>Inexistants</hair>
   ....: </coureur>
   ....: </coureurs>"""

In [28]: tree = etree.fromstring(s.encode())

In [35]: for user in tree.xpath('//coureurs/coureur'):
   ....:     for child in user:
   ....:         print(child.text,end=" ")
   ....:     print()
   ....:
Patrick Inexistants

Upvotes: 1

Related Questions