TypeError: cannot serialize None (type NoneType) in ElementTree alternative to if statements
Asked Answered
S

1

6

I can't find a practical solution in the documentation of ElementTree module for avoiding getting "TypeError: cannot serialize None (type NoneType)" when I try to set an attribute to None. Like here:

import xml.etree.ElementTree as ET
myvar = None
p = ET.Element('test')
b = ET.SubElement(p, 'tt')
b.set("last_update",myvar)
tree = ET.ElementTree(p)
tree.write('test.xml')

I know that I could use a series of if myvar is not None: ... but I would have to repeat the if statement many times. I was wondering if there is a way to avoid writing the attribute at all if the value of the attribute is None.

Scrogan answered 2/6, 2020 at 16:23 Comment(2)
Why don't you use myvar = "None"? Attribute values are strings.Am
@Am in my case I don't want None to appear in the xmlScrogan
M
0

I solved this with a subroutine to remove all None attributes from a tree. Just call this function before any serialization.

def removeNoneAttrib(elem):
    """Remove None attributes from XML tree"""
    elem.attrib = {
        k: elem.attrib[k]
        for k in elem.attrib
        if elem.attrib[k] is not None
    }
    for subelem in elem:
        removeNoneAttrib(subelem)

Example:

# ... the same as your code until the last line
removeNoneAttrib(tree.getroot())
tree.write('test.xml')

Note: If you had any check of the form elem.attrib[x] is None replace it with x not in elem.attrib.

Mensurable answered 30/1, 2023 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.