【问题标题】:How to import xml file data into a csv?如何将xml文件数据导入csv?
【发布时间】:2019-04-01 05:35:58
【问题描述】:

我正在将以下 xml 文件数据导入 csv 文件。

<State>
<Resident Id="100">
<Name>Sample Name</Name>
    <PhoneNumber>1234567891</PhoneNumber>
    <EmailAddress>sample_name@example.com</EmailAddress>
    <Address>
        <StreetLine1>Street Line1</StreetLine1>
        <City>City Name</City>
        <StateCode>AE</StateCode>
        <PostalCode>12345</PostalCode>
    </Address>
</Resident>
<Resident Id="101">
    <Name>Sample Name1</Name>
    <PhoneNumber>1234567891</PhoneNumber>
    <EmailAddress>sample_name1@example.com</EmailAddress>
    <Address>
        <StreetLine1>Current Address</StreetLine1>
        <City>Los Angeles</City>
        <StateCode>CA</StateCode>
        <PostalCode>56666</PostalCode>
    </Address>
</Resident>
.
.
.
.
</State>

尝试使用以下代码将数据导入 csv:

import csv
import xml.etree.ElementTree as  ET
tree = ET.parse("C:/Users/Public/Documents/sam.xml")
root = tree.getroot()
with open('C:/Users/Public/Documents/outp.csv', 'w') as f:
    fieldnames=['Id', 'Name', 'PhoneNumber','EmailAddress','StreetLine1','City',
                'StateCode','PostalCode']
    w= csv.DictWriter(f, fieldnames)
    w.writeheader()
    w.writerows(e.attrib for e in root.findall('.//file'))

我正在使用 Python 3 在 Jupyter(Anaconda) 笔记本中运行上述代码。

没有数据复制到 csv 文件中。仅将列/字段名称填充到 csv 文件中。

请告诉我为什么数据没有填充到 csv 中。 (当我在excel中打开xml文件时,数据是正确的。)

预期输出是

Id  Name    PhoneNumber EmailAddress    StreetLine1 City    StateCode   PostalCode
100 Sample Name 1234567891  sample_name@example.com Street Line1    City Name   AE  12345
101 Sample Name1    1234567891  sample_name1@example.com    Current Address Los Angeles CA  56666

【问题讨论】:

  • 你试过了吗w.writerows(e.attrib.text for e in root.findall('.//file'))

标签: python python-3.x


【解决方案1】:

下午好!

我使用 XML 和 CSV 处理了很多此类文件。将 CSV 转换为 XML 并不可怕,但您所追求的将需要您创建自己的数据结构。您提供给我们的示例 XML 来自该站点:

http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-xml-to-csv-using-python/

这些家伙实际上为您解决了这个问题!在上面粘贴的示例 XML 之后的页面向下滚动,您将找到 python 代码!

祝你文件转换未来好运!

Ethan J.

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2012-10-24
    • 1970-01-01
    • 2012-06-16
    • 2021-11-22
    • 2021-10-20
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多