I have the following XML in a string and I need to extract the names from the "col" tag. I'm trying to learn parsing but I haven't been able to hit the nail on the head. I don't know how to iterate it to extract the data from that label. Please if you can give me a hand. Thank you very much
This is my code:
import xml.etree.ElementTree as ET
data = '''<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<processOXIMessageResponse xmlns="urn:com:singun:webservice" xmlns:ns="urn:com:singun:webservice">
<ns1:processOXIMessageReturn xmlns:ns1="urn:com:singun:webservice">
<SingunDocument xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" protocol="OXI">
<sessionId xmlns="">1613762599483</sessionId>
<command xmlns="" echo="" xsi:type="ServiceProviderGetListResponse">
<serviceProviderTable>
<colHeading>Service Provider Id</colHeading>
<colHeading>Service Provider Name</colHeading>
<colHeading>Is Enterprise</colHeading>
<colHeading>Reseller Id</colHeading>
<row>
<col>Fluk-TEST</col>
<col>ATP 1</col>
<col>true</col>
<col />
</row>
<row>
<col>Beltran-TEST</col>
<col>ATP 2</col>
<col>true</col>
<col />
</row>
<row>
<col>ACME-TEST</col>
<col>ATP 3</col>
<col>true</col>
<col />
</row>
</serviceProviderTable>
</command>
</SingunDocument>
</ns1:processOXIMessageReturn>
</processOXIMessageResponse>
</soapenv:Body>
</soapenv:Envelope>
'''
myroot = ET.fromstring(data)
print("\nRecupera todas las etiquetas de primer hijo de la raíz:")
for x in myroot[0]:
print(x.tag, x.attrib)
All the best
A crude way of parsing this XML can be with the numeric elements of each level and finally with
findall()
:A slightly more elegant and pretty way to do the same thing is with
iter()
Read Parser XML documentation . For both cases, the output is: