Using XPath in ElementTree

Viewed 67830

My XML file looks like the following:

<?xml version="1.0"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19">
  <Items>
    <Item>
      <ItemAttributes>
        <ListPrice>
          <Amount>2260</Amount>
        </ListPrice>
      </ItemAttributes>
      <Offers>
        <Offer>
          <OfferListing>
            <Price>
              <Amount>1853</Amount>
            </Price>
          </OfferListing>
        </Offer>
      </Offers>
    </Item>
  </Items>
</ItemSearchResponse>

All I want to do is extract the ListPrice.

This is the code I am using:

>> from elementtree import ElementTree as ET
>> fp = open("output.xml","r")
>> element = ET.parse(fp).getroot()
>> e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount')
>> for i in e:
>>    print i.text
>>
>> e
>>

Absolutely no output. I also tried

>> e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount')

No difference.

What am I doing wrong?

5 Answers

One of the most straight forward approach and works even with python 3.0 and other versions is like below:

It just takes the root and starts getting into it till we get the specified "Amount" tag

 from xml.etree import ElementTree as ET
 tree = ET.parse('output.xml')
 root = tree.getroot()
 #print(root)
 e = root.find(".//{http://webservices.amazon.com/AWSECommerceService/2008-08-19}Amount")
 print(e.text)
Related