Python:将 XML 转换为 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31844713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Convert XML to CSV file
提问by pam
I have an XML file like this:
我有一个像这样的 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>
I'm trying to convert it to a CSV file like this:
我正在尝试将其转换为这样的 CSV 文件:
Data,Studyval
Date,Site
Info,age
Info,gender
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?
我的问题是,父母和孩子的名字都是一样的——“att”和“attval”。我如何告诉 Python 区分两者并给我输出?
I tried this:
我试过这个:
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.
它打印了两次相同的东西。
采纳答案by Havok
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.
不要使用该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))
Which gives:
这使:
$ python process.py
Data,Studyval
Data,Site
Info,age
Info,gender