Parse childs in XML python -
i have xml code like:
<?xml version='1.0' encoding="utf-8"?> <coureurs> <coureur> <nom>patrick</nom><hair>inexistants</hair> </coureur> </coureurs>
and want print that:
patrick inexistents etc... code : lxml import etree tree = etree.parse(file.xml) coureur in tree.xpath("/coureurs/coureur/nom"): print(user.text)
but returns blank, when do: user in tree.xpath("/coureurs/coureur/hair"): returns hair. should do?
i still not able reproduce issue xml , code provided. seems have left out lot of xml , , xpath
may not working if coureurs
not direct root of xml (or direct child) .
in such cases, can use following xpath each coureur
node in xml (that child of coureurs
node) -
//coureurs/coureur
this give <coureur>
tag elements xml , , ca iterate on print it's child's text . example code -
for user in tree.xpath('//coureurs/coureur'): 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]: user in tree.xpath('//coureurs/coureur'): ....: child in user: ....: print(child.text,end=" ") ....: print() ....: patrick inexistants
Comments
Post a Comment