使用Python中的元素树解析Xml,标记名称相同

时间:2014-09-08 09:47:20

标签: python xml parsing

我使用python来解析XML文件,但是我遇到了问题。我确定有一种方法可以解决它,但我是python的新手并解析xml ...

这里有一个xml的例子:

<TeamData Ref = "1">
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
</TeamData>
<TeamData Ref = "2">
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
</TeamData>

我希望将我的元素目标存储在团队参考的两个部分......我该怎么做?因为我试过了:

for iterators in child.iter("TeamData"):
                something_to_store(iterators.tag)

但我有所有8个目标的列表,没有teamdata ref的功能差异!

1 个答案:

答案 0 :(得分:1)

A.XML

<?xml version="1.0"?>
<data>

<TeamData Ref = "1">
    <Goal>a</Goal>
    <Goal>b</Goal>
    <Goal>c</Goal>
    <Goal>d</Goal>
</TeamData>

<TeamData Ref = "2">
    <Goal>e</Goal>
    <Goal>f</Goal>
    <Goal>g</Goal>
    <Goal>h</Goal>
</TeamData>
    </data>

对于每个teamdata,您需要再次迭代才能获得目标。所以创建dictonary,将ref name作为键,将目标作为值

import xml.etree.ElementTree as ET
tree = ET.parse('a.xml')
root = tree.getroot()
print root
dic={}
for i in root.iter('TeamData'):
    dic[i.attrib['Ref']]=[j.text for j in i]
print dic
#output {'1': ['a', 'b', 'c', 'd'], '2': ['e', 'f', 'g', 'h']}