簡體   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