Python:将XML转换为CSV文件

时间:2015-08-05 23:59:17

标签: python xml csv xpath elementtree

我有一个像这样的XML文件:

<hierachy>
    <att>
        <Order>1</Order>
        <attval>Data</attval>
        <children>
            <att>
                <Order>1</Order>
                <attval>Studyval</attval>
            </att>
            <att>
                <Order>2</Order>
                <attval>Site</attval>
            </att>
        </children>
    </att>
    <att>
        <Order>2</Order>
        <attval>Info</attval>
        <children>
            <att>
                <Order>1</Order>
                <attval>age</attval>
            </att>
            <att>
                <Order>2</Order>
                <attval>gender</attval>
            </att>
        </children>
    </att>
</hierachy>

我正在尝试将其转换为CSV文件,如下所示:

Data,Studyval
Date,Site
Info,age
Info,gender

我的问题是,父名和子名都是相同的 - 'att'和'attval'。我如何告诉Python区分两者并给我输出?

我试过了:

import xml.etree.cElementTree as ET

tree = ET.parse('input.xml')
rebase = tree.getroot()

list = []

for att in rebase.findall('att'):
        name = att.find('attval').text
        for each_att in att.findall('attval'):
            try:
                val = att.find('attval').text
                print name, val
            except AttributeError:
                print name

它打印了两次相同的东西。

1 个答案:

答案 0 :(得分:7)

不要使用findall函数,因为它会在整个树中查找att标记。只需按顺序从上到下迭代树,然后抓住它们中的相关元素。

from xml.etree import ElementTree
tree = ElementTree.parse('input.xml')
root = tree.getroot()

for att in root:
    first = att.find('attval').text
    for subatt in att.find('children'):
        second = subatt.find('attval').text
        print('{},{}'.format(first, second))

给出了:

$ python process.py 
Data,Studyval
Data,Site
Info,age
Info,gender