繁体   English   中英

解析xml文件的所有元素

[英]Parsing all the elements of an 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>

我喜欢得到一个包含所有标签和元素及其值的字典:

mydic = {"active":"0","platform_name":"octa2","sn":"123456", "fw_config":"octa3"}

在python中有没有一种有效的方法来做到这一点?

我试过解决你的问题

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 将是一个以标签为键的 OrderedDict。

使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM