简体   繁体   English

在XML python中解析子元素

[英]Parse childs in XML python

I have a XML code like: 我有一个类似的XML代码:

<?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. 但是,当我这样做时,它返回空白:对于tree.xpath(“ / coureurs / coureur / hair”)中的用户:它仅返回头发。 what should i do? 我该怎么办?

I am still not able to reproduce the issue with the xml and code you provided. 我仍然无法通过您提供的xml和代码重现该问题。 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) . 但是似乎您已经遗漏了很多xml,并且如果coureurs不是xml(或其直接子级)的直接根,则XPATH可能对您coureurs

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) - 在这种情况下,您可以使用以下XPATH来获取xml中的每个coureur节点(这是coureurs节点的子节点)-

//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 . 这将为您提供xml中的所有<coureur>标记元素,然后对其进行迭代以打印其子文本。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM