XML Python | SoloLearn: Learn to code for FREE!


XML Python

Hello, I need to know how to get an attribute of an xml child node with python. The xml looks something like this: <?xml version="1.0"?> <Transactions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Transaction> <GeneralData Ref="PX00103622" Type="AutofacturaComercial" Date="2020-02-20" Currency="EUR" BeginDate="2020-02-20" EndDate="2020-02-20" DeliveryAddrID="0" TaxIncluded="false" OnlyArchive="false" <DigitallyCertified>true</DigitallyCertified> </GeneralData> <Reference DNRef="14273107/14273106" PORef="6500009101" InvoiceRef="20NV022515" DNRefDate="2020-02-26" PORefDate="2020-02-11" InvoiceRefDate="2020-02-20" /> </References> . . . . </Transaction> </Transactions> You would need to get the data associated with Ref, Date and PORef; but I can't get it out

5/18/2020 2:33:43 PM

David Chichon Sanchez

2 Answers

New Answer


Check the xml module in python ''' data associated with Ref, Date and PORef; ATTENTION!! https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter ''' import xml.etree.ElementTree as ET tree = ET.parse('example.xml') root = tree.getroot() attributes = [] search_attributes = ('Ref', 'Date', 'PORef') for elem in root: for _elem in elem: attributes.append(_elem.attrib) for i in attributes: for k, v in i.items(): if k in search_attributes: print(f'{k}:{v}')


I hope it will help you