<p>我的建议是按如下方式组织数据:</p>
<pre class="lang-xml prettyprint-override"><code><root>
<subroot id="someID">
<value id="1">a</value>
<value id="2">b</value>
<value id="3">c</value>
<value id="4">d</value>
<value id="5">2</value>
<value id="6">3</value>
<value id="other">xyz</value>
</subroot>
<subroot id="anotherID">
<value id="1">aa</value>
<value id="2">bb</value>
<value id="3">cc</value>
<value id="4">11</value>
<value id="5">22</value>
<value id="6">33</value>
<value id="other">xxyyzz</value>
</subroot>
</root>
</code></pre>
<p>然后,为了解析,我建议使用etree库——它位于Python的标准库中,而且我发现使用它比使用其他库要好得多。这只是一个简单的例子,遍历子路径和值元素并提取数据。你知道吗</p>
<pre class="lang-py prettyprint-override"><code>from xml.etree import ElementTree
xml = ElementTree.parse("test.xml")
root = xml.getroot()
all = {}
for group in root.findall("subroot"):
temp = {}
for value in group.findall("value"):
temp[value.get("id")] = value.text
all[group.get("id")] = temp
</code></pre>
<p>所有这些都将是:</p>
<pre class="lang-py prettyprint-override"><code>{'someID': {'1': 'a', '3': 'c', '2': 'b', '5': '2', '4': 'd', '6': '3', 'other': 'xyz'}, 'anotherID': {'1': 'aa', '3': 'cc', '2': 'bb', '5': '22', '4': '11', '6': '33', 'other': 'xxyyzz'}}
</code></pre>
<p>您也可以作为<a href="http://docs.python.org/py3k/tutorial/datastructures.html?highlight=dict%20comprehension#dictionaries" rel="nofollow">dict comprehension</a>执行此操作:</p>
<pre class="lang-py prettyprint-override"><code>all = {group.get("id"): {value.get("id"): value.text for value in group.findall("value")} for group in root.findall("subroot")}
</code></pre>
<p>请注意,这是一个有点难以阅读,并会崩溃,如果你试图做任何更复杂的。你知道吗</p>