Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml.etree.ElementTree >> Python >> How to access child element and make assertions

I am using PyTest to validate xml api response. Getting following response(response.content) from api request

b'<?xml version="1.0" encoding="UTF-8"?>
<Result0>
<Result1>
<Result3>
<Id>2</Id>
<ItemId>https://purchanse.com/62/E00036415</ItemId>
<Place>kpi:62_CS415-TEN-1080p25-ABC</Place>
<Marks>12</Marks>
<SubId>9, 8</SubId>
<Description>https://purchanse.com/62/E00036416</Description>
</Result3>
<Result4>
<Id>2</Id>
<ItemId>https://purchanse.com/64/E00036417</ItemId>
<Place>kpi:63_CS415-TEN-1080p25-XYZ</Place>
<Marks>12</Marks>
<SubId>9</SubId>
<Description>https://purchanse.com/64/E00036416</Description>
</Result4>
</Result1>
</Result0>'

in test function I have this code

def test_CheckResponseContent():
    element = et.fromstring(response.content)
    print("element", element)  # Getting <Element 'Result0' at 0x04A88C58> as output
    links = element.find("Result0/Result1")
    print("L:", links)  # Returns 'None'

element = et.fromstring(response.content)
    for child in element.iter('*'):
        print(child.tag)

I want to make assertions like

Marks == 12
Id == 2
ItemId != "https://purchanse.com/62/E00036416"

How can I parse the XML for this?
Can someone please help

like image 257
Finch Avatar asked Jul 09 '26 20:07

Finch


1 Answers

You have multiple tags with mentioned names, so the corresponding set of checks should be performed separately, for each parent of these tags.

To do it, try the following code, maybe without print statements:

for it in element.findall('Result1/*'):
    print(it.tag)
    mrks = it.findtext('Marks')
    id = it.findtext('Id')
    itmId = it.findtext('ItemId')
    print(mrks, id, itmId)
    assert mrks == '12'
    assert id == '2'
    assert itmId != 'https://purchanse.com/62/E00036416'
like image 89
Valdi_Bo Avatar answered Jul 12 '26 10:07

Valdi_Bo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!