sunnysideup
sunnysideup

Reputation: 75

How do I search an XML tree with two different criteria using python?

I am stuck with this problem for the past few hours.

This is how the XML looks like

    <xmlblock>
        <data1>
              <username>someusername</username>
              <id>12345</id>
        </data1>
        <data2>
             <username>username</username>
             <id>11111</id>
        </data1>
    </xmlblock>

The problem is this:

I need the username when it matches a given id.

I am not sure how to do a double search using iterfind or any other lxml module in python.

Any help will be greatly appreciated. Thanks!

Upvotes: 0

Views: 161

Answers (3)

Daenyth
Daenyth

Reputation: 37431

Here's an example using lxml and xpath


>>> xml = '''
    <xmlblock>
        <data1>
              <username>someusername</username>
              <id>12345</id>
        </data1>
        <data2>
             <username>username</username>
             <id>11111</id>
        </data2>
    </xmlblock>'''
>>> doc = lxml.etree.fromstring(xml)
>>> matching_nodes = doc.xpath('//id[text()="11111"]/../username')
>>> for node in matching_nodes:
        print node.text
username

Upvotes: 0

Can&#39;t Tell
Can&#39;t Tell

Reputation: 13416

If you are ok with using minidom the following should work

from xml.dom import minidom
doc = minidom.parseString('<xmlblock><data1><username>someusername</username><id>12345</id></data1><data2><username>username</username><id>11111</id></data2></xmlblock>')
username = [elem.parentNode.getElementsByTagName('username') for elem in doc.getElementsByTagName('id') if elem.firstChild.data == '12345'][0][0].firstChild.data
print username

Upvotes: 0

Niek de Klein
Niek de Klein

Reputation: 8824

A (probably not the best) solution

>>> id_to_match = 12345
>>> for event, element in cElementTree.iterparse('xmlfile.xml'):
...     if 'data' in element.tag:
...        for data in element:
...            if data.tag == 'username':
...                username = data.text
...            if data.tag == 'id':
...                if data.text == id_to_match:
...                    print username
someusername                 

Upvotes: 2

Related Questions