1

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 ?

1 Answer 1

1

Use //continent[./country/@countryname="India"]/@region xpath expression:

>>> import lxml.etree as ET
>>> 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>
... """
>>> root = ET.fromstring(xmldata)
>>> print root.xpath('//continent[./country/@countryname="India"]/@region')
['Asia']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks , can you please give me some links for learning xpath experssions ?
@Fledgling don't like to refer to w3c schools but there is a lot of info there. Also, you can experiment with the xpaths online, see xpathtester.

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.