1

From the sample xml below

<?xml version="1.0"?>
    <data>
        <country>
            <name>Liechtenstein</name>
            <rank>1</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country>
            <name>Singapore</name>
            <rank>4</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country>
            <name>Panama</name>
            <rank>68</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>

Using Python ElementTree

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')


for elem in tree.iter(tag='name'):
    print (elem.tag)

displays three name elements. How can I retrive just one name element <name>Panama</name> with a specfic text.

for elem in tree.iter(tag="name='panama'"): not working

2 Answers 2

2

You could consider using xpath in lxml. Using text() enables you to find 'Panama' as the content of an element quickly. Once you have done that you can navigate to neighbouring information items for the same country.

>>> from lxml import etree
>>> tree = etree.parse('test.xml')
>>> tree.xpath('.//name/text()')
['Liechtenstein', 'Singapore', 'Panama']
>>> for item in tree.xpath('.//name/text()'):
...     if item == 'Panama':
...         for cousins in item.getparent().getparent().getchildren():
...             cousins.text
...             
'Panama'
'68'
'2011'
'13600'
Sign up to request clarification or add additional context in comments.

Comments

1
import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
countries = tree.findall("country")
for country in countries:
    name = country.find("name")
    if name.text == "Panama":
        print(name.text)

Also, please note that your xml is not well formed. You have an ] instead of an > in line 19 of test.xml

Comments

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.