Nickpick
Nickpick

Reputation: 6587

Adding subelement with ElementTree

The below code, which should add a subelemenet to a given XML element, gives the error:

xml.SubElement(new,xml.Element(self.XMLEntriesList['RiverCallPower'])) TypeError: must be xml.etree.ElementTree.Element, not None

But when I check, the element in question is confirmed to be an Element, and not None.

self.XMLEntriesList['RiverCallPower']
Out[3]: Element 'RiverCallPower' at 0x04B83420

What am I doing wrong?

    import xml.etree.ElementTree as xml
    self.tree = xml.parse('strategies.xml')
    self.root = self.tree.getroot()
    ...
    new=self.root.append(xml.Element('newElement'))
    xml.SubElement(new,xml.Element(self.XMLEntriesList['RiverCallPower']))

Upvotes: 1

Views: 664

Answers (1)

har07
har07

Reputation: 89285

I suspect the problem is not in the XMLEntriesList['RiverCallPower'] part, but the new variable that is None. And that happen because append() simply adds the new element to the list of root element's children and doesn't return anything. Try this way :

.......
new = xml.Element('newElement')
self.root.append(new)
xml.SubElement(new,xml.Element(self.XMLEntriesList['RiverCallPower']))

Upvotes: 2

Related Questions