Python findall() not working like I think it should

Viewed 54

In python, I'm attempting to collect the nodes of my xml file with the tag 'offer' whose direct parent is 'Offers'. When I run the code, 'offers is empty. Any help is greatly appreciated.

import xml.etree.ElementTree as ET
tree = ET.parse('xmlResponseFile.xml')
root = tree.getroot()
offers = tree.findall('.//Offers')

I've also tried

offers = tree.findall('./Offers')
offers = tree.findall('Offers')

xmlResponseFile

<?xml version="1.0"?><ReceiveMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><ReceiveMessageResult><Message><MessageId>fed67b06-77df-4bc2-9296-1949bef0b30b</MessageId>
<ReceiptHandle>your Handle Num<ReceiptHandle>
<MD5OfBody>e6ac195389a31a56db38c8c2084559d0</MD5OfBody><Body><Notification>

<NotificationMetaData>
    <NotificationType>AnyOfferChanged</NotificationType>
</NotificationMetaData>

<NotificationPayload>
    <AnyOfferChangedNotification>
        <OfferChangeTrigger>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>071780397X</ASIN>
            <ItemCondition>used</ItemCondition>
            <TimeOfOfferChange>2022-07-16T16:48:05.150Z</TimeOfOfferChange>
        </OfferChangeTrigger>
        <Offers>
            <Offer>
                <SellerId>A3BG1EQR3FDLCW</SellerId>
            </Offer>

            <Offer>
                <SellerId>A1F5ORSGF7UA9M</SellerId>
            </Offer>

            <Offer>
                <SellerId>AZPXF5FTGDD0O</SellerId>
            </Offer>
        </Offers>
    </AnyOfferChangedNotification>
</NotificationPayload>
</Notification>
</Body></Message></ReceiveMessageResult><ResponseMetadata><RequestId>1dee7f72-db03-577f-b107-243e35bfdac6</RequestId></ResponseMetadata></ReceiveMessageResponse>

1 Answers

You have to deal with the namespaces in your xml (which, at least in your question, is not well-formed). Assuming your xml is fixed, you can select, for example, the seller ID in each offer like this:

for seller in tree.findall('.//{*}Offers//{*}Offer//{*}SellerId'):
     print(seller.text.strip())

Output should be:

A3BG1EQR3FDLCW
A1F5ORSGF7UA9M
AZPXF5FTGDD0O
Related