For this xml,
xmldata="""
<locations>
<continent region="Africa" >
<country id="84" countryname="Algeria" ></country>
</continent>
<continent region="Asia" >
<country id="84" countryname="India" ></country>
</continent>
<continent region="America" >
<country id="84" countryname="Mexico" ></country>
</continent>
</locations>
"""
I am trying to get region name using country name , If country name is India then code should return Asia.
What I have tried ,
import lxml.etree as ET
root = ET.fromstring(xmldata)
flag=False
continent=""
country=""
for neighbor in root.iter('continent'):
for i in neighbor.iter("country"):
if i.attrib.get('countryname')=="India":
flag=True
continent=neighbor.attrib.get('region')
country=i.attrib.get('countryname')
if flag==True:
break
print 'Continent is ',continent , 'And country is ', country
This code works , but it is not convenient way to do this.
How can i achieve this using xpath expression ?