python - How to get specific XML tag values? -


is there way specific values of xml tag?

<country rank="0">   <name>xyz</name>   <place>abcd</intvalue>  </country> <country rank="1">   <name>xyz1</name>   <place>abcd1</intvalue>  </country> <country rank="2">   <name>xyz2</name>   <place>abcd2</intvalue>  </country> 

how can place of country of particular rank?

below code results text of xml tags. need traverse through specific xpaths.

from xml.etree import elementtree  open('file.xml', 'rt') f:     tree = elementtree.parse(f)  node in tree.iter():     print node.tag     print node.text 

using xpaths:

[place.text country in e.findall(".//country[@rank='1']") place in country.iter("place")] 

where e tree or element root. rank value in xpath ".//country[@rank='1']" can used change desired rank, can make function like:

def get_places_by_rank(e, rank):     xpath = ".//country[@rank='{}']".format(rank)     return [place.text country in e.findall(xpath) place in country.iter("place")] 

and use like:

>>> e=et.fromstring(""" ... <countries> ...     <country rank="0"> ...         <name>xyz</name> ...         <place>abcd</place> ...     </country> ...     <country rank="1"> ...         <name>xyz1</name> ...         <place>abcd1</place> ...     </country> ...     <country rank="2"> ...         <name>xyz2</name> ...         <place>abcd2</place> ...     </country> ...  </countries>""") >>> >>> get_places_by_rank(e, 1) ['abcd1'] >>> get_places_by_rank(e, 2) ['abcd2'] >>> get_places_by_rank(e, 3) [] >>> get_places_by_rank(e, 0) ['abcd'] 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -