我正在将以下 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
最佳答案
下午好!
我使用 XML 和 CSV 进行了大量此类文件工作。将 CSV 转换为 XML 并不可怕,但是您所追求的将需要您创建自己的数据结构。您提供给我们的示例 XML 来自以下站点:
http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-xml-to-csv-using-python/
这些人实际上已经为你解决了这个问题!在上面粘贴的示例 XML 后面的页面上向下滚动,您将找到 python 代码!
祝您的文件转换 future 好运!
伊森·J.
关于python - 如何将 xml 文件数据导入到 csv 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445568/