[英]Parsing all the elements of an xml file
Let's assume I have the following xml file:假设我有以下 xml 文件:
<test_suite>
<test_case active="0">
<platform name="octa2">
<sn>123456</sn>
</platform>
<fw_config>octa3</fw_config>
</test_case>
</test_suite>
I like to get a dictionary with the all the tags and elements and their values:我喜欢得到一个包含所有标签和元素及其值的字典:
mydic = {"active":"0","platform_name":"octa2","sn":"123456", "fw_config":"octa3"}
Is there an efficient way of doing this in python?在python中有没有一种有效的方法来做到这一点?
I tried solving your problem我试过解决你的问题
import xmltodict
x = """
<test_suite>
<test_case active="0">
<platform name="octa2">
<sn>123456</sn>
</platform>
<fw_config>octa3</fw_config>
</test_case>
</test_suite>
"""
print xmltodict.parse(x)
O/P will be a OrderedDict with tags as keys. O/P 将是一个以标签为键的 OrderedDict。
Using xml.etree.ElementTree
:使用xml.etree.ElementTree
:
>>> import xml.etree.ElementTree as ET
>>>
>>> root = ET.fromstring('''
... <test_suite>
... <test_case active="0">
... <platform name="octa2">
... <sn>123456</sn>
... </platform>
... <fw_config>octa3</fw_config>
... </test_case>
... </test_suite>
... ''')
>>>
>>> [{
... 'active': test_case.get('active'),
... 'platform_name': test_case.find('platform').get('name'),
... 'sn': test_case.find('platform/sn').text,
... 'fw_config': test_case.find('fw_config').text,
... } for test_case in root.iterfind('.//test_case')]
[{'platform_name': 'octa2', 'sn': '123456', 'active': '0', 'fw_config': 'octa3'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.