我正在学习Python,并试图从任何XML文件中提取所有标记和相应值的列表。这是我目前为止的代码。在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 ([], [], [])
对于这样的XML输入:
^{pr2}$
这个输出是标记、值和属性的多个列表。这个很好用。在['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'}]]
但我的问题是我需要包括父标记和子标记的标记。下面是我的目标实际输出:['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']
如何使用Python实现这一点?或者还有其他的方法吗?在