AttributeError: Element instance has no attribute '__float__' in Python

1.7k Views Asked by At

I get this error when I run my script

AttributeError: Element instance has no attribute '__float__'

My code looks like this:

def populate():
    parsedfiles = minidom.parse('C:\Users\User\Downloads\New folder\StreetTrees_ArbutusRidge.xml')
    treelist = parsedfiles.getElementsByTagName('StreetTree')
    for alltrees in treelist:
        treeId = alltrees.getAttribute('TreeID')
        neighbourhood = alltrees.getElementsByTagName('NeighbourhoodName')
        commonName = alltrees.getElementsByTagName('CommonName')
        diameter = alltrees.getElementsByTagName('Diameter')[0]
        diameter = float(diameter)
        streetNumber = alltrees.getElementsByTagName('CivicNumber')
        street = alltrees.getElementsByTagName('StdStreet')
        lat = 0
        lon = 0
        add_tree(treeId=treeId, neighbourhood=neighbourhood, commonName=commonName,
                 diameter=diameter, streetNumber=streetNumber, street=street, lat=0, lon=0)

I think I'm misinterpreting the diameter but I don't know how to fix it.

1

There are 1 best solutions below

0
On BEST ANSWER

diameter is a DOM Element:

diameter = alltrees.getElementsByTagName('Diameter')[0]

It is not directly convertable to a float, because that's not textual data; you probably want the text contained in the element:

diameter = alltrees.getElementsByTagName('Diameter')[0]
diameter = float(diameter.firstChild.nodeValue)

Note that the W3C DOM is rather a pain to work with; you may want to look into the more Pythonic ElementTree API instead:

parsedfiles = etree.parse(r'C:\Users\User\Downloads\New folder\StreetTrees_ArbutusRidge.xml')
for alltrees in parsedfiles.findall('.//StreetTree'):
    treeId = alltrees. attrib['TreeID']
    neighbourhood = alltrees.findall('NeighbourhoodName')
    commonName = alltrees.findall('CommonName')
    diameter = float(alltrees.find('Diameter').text)
    streetNumber = alltrees.findall('CivicNumber')
    street = alltrees.findall('StdStreet')
    add_tree(treeId=treeId, neighbourhood=neighbourhood, commonName=commonName,
             diameter=diameter, streetNumber=streetNumber, street=street,
             lat=0, lon=0)

where I am assuming that the various elements you are looking for are directly contained in the <StreetTree> element.