0

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?

4
  • sorry its not he exeact code the xml is wrong on that one but for mine its right. Commented Aug 7, 2015 at 18:10
  • i edited it. corrected the </user> Commented Aug 7, 2015 at 18:12
  • 1
    I do not think that is the correct xml either, if that was correct xml , then the xpath - for user in tree.xpath("/users/user/hair"): would not be working, it would not even return the hair, but you said it returns the hair in your question. Commented Aug 7, 2015 at 18:12
  • aand now? (this is the real code) Commented Aug 7, 2015 at 18:21

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

11 Comments

No , those are my interpreter prompt , use the code from above the example/demo .
But, in the code above (mine) where do you see <user>?
Sorry didn't get your question. what do you mean?
why : for user in tree.xpath
and not : for coureur in tree.xpath?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.