如何将xml转换成结构化的cs

2024-10-02 22:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下xml数据,我想将其转换为csv:

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country2 name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country2>
    <country3 name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country3>
</data>

如何在csv中将每个国家/地区行表示为一行,并包含每个国家/地区内的所有属性。我不知道如何阅读多个国家。你知道吗

我有以下代码:

import os
from xml.etree import ElementTree as ET



rootElement = ET.parse("/Users/testuser/Desktop/test.XML").getroot()


with open('/Users/testuser/Desktop/output.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, lineterminator='\n')


    for subelement in rootElement:
        for subsub in subelement:
            print subsub.tag
            writer.writerows(subsub.items())
            for subsubsub in subsub:
                print subsubsub.items()
                writer.writerows(subsubsub.items())

不幸的是,这并没有给我想要的输出。在我的CSV中,我希望每一行代表一个国家。所以第一行是country,第二行是country2。然后每列应该给我子元素的值。所以在我的csv中,A1是国家/名称,A2是国家/等级等等。B1是country2/name,B2是country2/rank。。你知道吗

目前我得到以下输出:

enter image description here


Tags: csvnamefor国家yearcountryyeswriter
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:18
import csv
import xml.etree.ElementTree as ET
tree = ET.parse('/tmp/test123.xml')
root = tree.getroot()
doc = open('/tmp/output123.csv', 'w')
for child in root:
    for country in root.findall(str(child.tag)):
        rec = '%s,%s,%s' %(str(child.tag), str(country.find('rank').text), str(country.find('gdppc').text))
    for neighbor in country.findall('neighbor'):
        rec= rec+ ',' + str(neighbor.attrib['name']) +',' + str(neighbor.attrib['direction'])
    doc.write(rec + '\n')
doc.close()

你知道吗输出.csv你知道吗

country,2,141100,Austria,E,Switzerland,W
country2,5,59900,Malaysia,N
country3,69,13600,Costa Rica,W,Colombia,E

相关问题 更多 >