I'm learning Python and I'm trying to extract lists of all tags and corresponding values from any XML file. This is my code so far.
def ParseXml(XmlFile):
try:
parser = etree.XMLParser(remove_blank_text=True, compact=True)
tree = ET.parse(XmlFile, parser)
root = tree.getroot()
ListOfTags, ListOfValues, ListOfAttribs = [], [], []
for elem in root.iter('*'):
Tag = elem.tag
ListOfTags.append(Tag)
value = elem.text
if value is not None:
ListOfValues.append(value)
else:
ListOfValues.append('')
attrib = elem.attrib
if attrib:
ListOfAttribs.append([attrib])
else:
ListOfAttribs.append([])
print('%s File parsed successfully' % XmlFile)
return (ListOfTags, ListOfValues, ListOfAttribs)
except Exception as e:
print('Error while parsing XMLs : %s : %s' % (type(e), e))
return ([], [], [])
For an XML input like this:
<?xml version="1.0" encoding="UTF-8"?>
<Application Version="2.01">
<UserAuthRequest>
<VendorApp>
<AppName>SING</AppName>
</VendorApp>
</UserAuthRequest>
<ApplicationRequest ID="12-123-AH">
<GUID>ABD45129-PD1212-121DFL</GUID>
<Type tc="200">Streaming</Type>
<File></File>
<FileExtension VendorCode="200">
<Result>
<ResultCode tc="1">Success</ResultCode>
</Result>
</FileExtension>
</ApplicationRequest>
</Application>
This output is multiple lists of tags, values and attributes. This is working fine.
['Application', 'UserAuthRequest', 'VendorApp', 'AppName', 'ApplicationRequest', 'GUID', 'Type', 'File', 'FileExtension', 'Result', 'ResultCode']
['', '', '', 'SING', '', 'ABD45129-PD1212-121DFL', 'Streaming', '', '', '', 'Success']
[[{'Version': '2.01'}], [], [], [], [{'ID': '12-123-AH'}], [], [{'tc': '200'}], [], [{'VendorCode': '200'}], [], [{'tc': '1'}]]
But my problem is that i need the tags including the parent and child tags. Like below is actual output I'm targetting:
['Application', 'UserAuthRequest', 'UserAuthRequest.VendorApp', 'UserAuthRequest.VendorApp.AppName', 'ApplicationRequest', 'ApplicationRequest.GUID', 'ApplicationRequest.Type', 'ApplicationRequest.File', 'ApplicationRequest.File.FileExtension', 'ApplicationRequest.File.FileExtension.Result', 'ApplicationRequest.File.FileExtension.Result.ResultCode']
How do i make this happen with Python? or is there any other alternate way to do this?
Application.UserAuthRequestandApplication.ApplicationRequest. Also, there's noApplicationRequest.File.*in the xml. - CristiFati