【问题标题】:problem with converting XML file to CSV file in python在python中将XML文件转换为CSV文件的问题
【发布时间】:2022-01-08 17:50:55
【问题描述】:

我使用下面的代码将 XML 转换为 CSV 文件

但结果是: AttributeError: 'NoneType' 对象没有属性 'text'

谁能帮忙?


import xml.etree.ElementTree as Xet
import pandas as pd
  
cols = ["Id", "UserId", "Name", "Date", "Class", "TagBased"]
rows = []

xmlparse = Xet.parse('Badges.xml')
root = xmlparse.getroot()


for i in root:
    Id = i.find("Id").text
    userId = i.find("UserId").text
    name = i.find("Name").text
    date = i.find("Date").text
    Class = i.find("Class").text
    tagBased = i.find("TagBased").text
  
    rows.append({
                 "Id": Id,
                 "UserId": userId,
                 "Name": name,
                 "Date": date,
                 "Class": Class,
                 "TagBased": tagBased  
                })
  
df = pd.DataFrame(rows, columns=cols)
  
# Writing dataframe to csv
df.to_csv('output.csv')

我的数据如:

<badges> 
<row Id="1" UserId="2" Name="Autobiographer" Date="2014-04-17T00:58:09.973" Class="3" TagBased="False" />
<row Id="2890885" UserId="6775155" Name="Yearling" Date="2021-12-05T03:07:26.740" Class="2" TagBased="False" /> 
<row Id="2890886" UserId="5298879" Name="Yearling" Date="2021-12-05T03:07:26.740" Class="2" TagBased="False" /> 
</badges>

【问题讨论】:

  • 您的 i 节点没有具有其中一个名称的子元素。 docs.python.org/3/library/…。在引用 .text 之前检查 None
  • 我的数据是这样的,怎么办?
  • 那些不是子节点,而是节点的属性。您应该能够像这样访问它们:i.attrib.get("Id")。让我知道它是否有效。请不要在 cmets 中添加其他信息,而是编辑问题!
  • 成功了,谢谢!

标签: python xml csv converters


【解决方案1】:

上市[Python.Docs]: xml.etree.ElementTree - The ElementTree XML API

这是一个更简单的变体。

code00.py

#!/usr/bin/env python

import sys
from xml.etree import ElementTree as ET
import pandas as pd


COLS = ["Id", "UserId", "Name", "Date", "Class", "TagBased"]

def main(*argv):
    tree = ET.parse("./badges.xml")
    root = tree.getroot()
    rows = []
    for i in root:
        rows.append({col: i.attrib.get(col) for col in COLS})
        # The line above does the same thing as the 4 (commented) lines below. Listed them here for simplicity.
        #d = {}
        #for col in COLS:
        #    d[col] = i.attrib.get(col)
        #rows.append(d)

    df = pd.DataFrame(rows, columns=COLS)
    df.to_csv("./output.csv")


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q070634926]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> dir /b
badges.xml
code00.py

[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" code00.py
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32


Done.

[prompt]> dir /b
badges.xml
code00.py
output.csv

[prompt]> type output.csv
,Id,UserId,Name,Date,Class,TagBased
0,1,2,Autobiographer,2014-04-17T00:58:09.973,3,False
1,2890885,6775155,Yearling,2021-12-05T03:07:26.740,2,False
2,2890886,5298879,Yearling,2021-12-05T03:07:26.740,2,False

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 2020-10-07
    • 2016-01-07
    • 1970-01-01
    • 2019-02-02
    • 2021-05-08
    • 2021-11-21
    • 2011-03-05
    相关资源
    最近更新 更多