Python:将XML转换为CSV文件 [英] Python: Convert XML to CSV file

查看:828
本文介绍了Python:将XML转换为CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an XML file like this:

<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文件,如下所示:

I'm trying to convert it to a CSV file like this:

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

我的问题是,父母和孩子的名字都是一样的-'att'和'attval'.如何告诉Python区分两者并给我输出?

My problem is, both the parent and child names are the same- 'att' and 'attval'. How do I tell Python to distinguish between the both and give me the output?

我尝试过:

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

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

and it printed the same things twice.

推荐答案

请勿使用findall函数,因为它将在整个树中查找att标签.只需从上到下依次遍历树并抓住其中的相关元素即可.

Do not use the findall function, as it will look for att tags in the whole tree. Just iterate the tree in order from top to bottom and grab the relevant elements in them.

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

这篇关于Python:将XML转换为CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆