0

I use code below to convert XML to CSV file

but the result is : AttributeError: 'NoneType' object has no attribute 'text'

Can anyone help?


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')

MY data like:

<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>
3
  • Your i node doesn't have an subelement with one of the names. docs.python.org/3/library/…. Check for None before referring .text. Commented Jan 8, 2022 at 17:53
  • My data like this, how can I do it? <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> Commented Jan 8, 2022 at 17:58
  • 1
    Those are not subnodes but attributes of the node. You should be able to access them like: i.attrib.get("Id"). Let me know if it works. And please do not add additional info in comments, edit the question instead! Commented Jan 8, 2022 at 18:01

1 Answer 1

1

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

Here's a simpler variant.

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)

Output:

[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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.