Python3将XML解析成字典

2024-09-28 21:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

原来的帖子似乎太模糊了,所以我缩小了这篇文章的重点。我有一个XML文件,我想从中提取特定分支的值,我很难理解如何有效地导航XML路径。考虑下面的XML文件。有几个<mi>分支。我想存储某些分支的<r>值,但不存储其他分支的值。在这个例子中,我想要counter1和counter3的<r>值,而不是counter2。在

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Data.xsl" ?>
<!DOCTYPE mdc SYSTEM "Data.dtd">
<mdc xmlns:HTML="http://www.w3.org/TR/REC-xml">
<mfh>
<vn>TEST</vn>
<cbt>20140126234500.0+0000</cbt>
</mfh>
<mi>
    <mts>20140126235000.0+0000</mts>
    <mt>counter1</mt>
    <mv>
        <moid>DEFAULT</moid>
        <r>58</r>
    </mv>
</mi>
<mi>
    <mts>20140126235000.0+0000</mts>
    <mt>counter2</mt>
    <mv>
        <moid>DEFAULT</moid>
        <r>100</r>
    </mv>
</mi>
<mi>
    <mts>20140126235000.0+0000</mts>
    <mt>counter3</mt>
    <mv>
        <moid>DEFAULT</moid>
        <r>7</r>
    </mv>
</mi>
</mdc>

在此基础上,我将构建一个包含以下内容的元组: ('20140162234500.0+0000',58,7) 其中2014016234500.0+0000取自<cbt>,58取自<mi>元素的<r>值,7取自具有<mt>counter3</mt>的{}元素。在

我想使用xml.etree.cElementTree,因为它似乎是标准的,而且对于我的目的来说应该是非常有用的。但是我在导航树和提取我需要的值方面遇到了困难。下面是我尝试过的一些方法。在

^{pr2}$

从伪代码的角度来看,我想做的是:

find the <cbt> value and store it in the first position of the tuple.
find the <mi> element where <mt>counter1</mt> exists and store the <r> value in the second position of the tuple.
find the <mi> element where <mt>counter3</mt> exists and store the <r> value in the third position of the tuple.

我不清楚何时使用element.iter()或{}。另外,在函数中使用XPath,或者无法提取我需要的信息,我也不太幸运。在

谢谢, 生锈的


Tags: thedefault分支xmlfindmtsmimt
1条回答
网友
1楼 · 发布于 2024-09-28 21:22:12

开始于:

import xml.etree.cElementTree as ET  # or with try/except as per your edit

xml_data1 = """<?xml version="1.0"?> and the rest of your XML here"""
tree = ET.fromstring(xml_data)  # or `ET.parse(<filename>)`
xml_dict = {}

现在,tree有了xml树,xml_dict将是您试图获得结果的字典。在

^{pr2}$

计数器位于'mi'

^{3}$

此时,xml_dict是:

>>> xml_dict
{'counter2': '100', 'counter1': '58', 'cbt': '20140126234500.0+0000', 'counter3': '7'}

一些缩短,尽管可能不可读:for elem in tree.findall('mi'):循环中的代码可以是:

xml_dict[elem.find('mt').text] = elem.find('mv').find('r').text
# that combines the key/value extraction to one line

或者更进一步地说,构建xml_dict只需两行,计数器在前面,cbt之后:

xml_dict = {elem.find('mt').text: elem.find('mv').find('r').text for elem in tree.findall('mi')}
xml_dict['cbt'] = tree.find('mfh').find('cbt').text

编辑:

From the docs^{}只查找带有标记的元素,这些元素是当前元素的直接子元素。在

find()只找到第一个直接子级。在

^{}递归地遍历所有元素。在

相关问题 更多 >