Search code examples
pythonxmlcsvexport-to-csv

Converting unusual XML file to CSV using Python


I'm having an issue with my XML file. I would like to achieve the same as in: https://www.delftstack.com/howto/python/xml-to-csv-python/

However, my XML file looks a bit different, for example:

<students>
<student name="Rick Grimes" rollnumber="1" age="15"/>
<student name="Lori Grimes" rollnumber="2" age="16"/>
<student name="Judith Grimes" rollnumber="4" age="13"/>
</students>

The code specified in the link does not work with this formatting.

from xml.etree import ElementTree

tree = ElementTree.parse("input.xml")
root = tree.getroot()

for student in root:
    name = student.find("name").text
    roll_number = student.find("rollnumber").text
    age = student.find("age").text
    print(f"{name},{roll_number},{age}")

I have very little coding experience, so hoping someone on here can help me out.

Expected result:

Rick Grimes,1,15 Lori Grimes,2,16 Carl Grimes,3,14 Judith Grimes,4,13

Actual result:

AttributeError: 'NoneType' object has no attribute 'text'


Solution

  • You cannot get the text if there aren't any text to get. Instead you want to use .attrib[key] as you have the values as attributes.

    I have modified your example so that it will work with your XML file.

    from xml.etree import ElementTree
    
    tree = ElementTree.parse("input.xml")
    root = tree.getroot()
    
    for student in root:
        name = student.attrib["name"]
        roll_number = student.attrib["rollnumber"]
        age = student.attrib["age"]
        print(f"{name},{roll_number},{age}")
    

    I hope this will help you.