Hi,
I have this sort of XML:
<property name="Acceleration">
<unit>
<unitname>meter / sq. second</unitname>
</unit>
<unit>
<unitname>meter / sq. minute</unitname>
</unit>
<unit>
<unitname>meter / sq. hour</unitname>
</unit>
...
I can delete the ‘property’ node with:
class Converter(object):
def __init__(self, xmlFile, parent = None):
self.xmlFile = xmlFile
self.tree = ElementTree()
self.xmlDoc = self.tree.parse(self.xmlFile)
self.lstProperty = self.xmlDoc.getiterator("property")
def DeleteProperty(self, strProperty):
for property in self.lstProperty:
if property.attrib"name"] == strProperty:
self.xmlDoc.remove(property)
self.tree.write(self.xmlFile, "utf-8")
return True
But I just can’t delete any of the ‘unit’ nodes no matter what I try. I’ve tried these:
def DeleteUnit(self, strProperty, strUnit):
units = self.xmlDoc.findall("property/unit")
for unit in units:
if unit.text == strUnit:
self.xmlDoc.remove(units) #also tried 'units.remove(unit)'
self.tree.write(self.xmlFile, "utf-8")
return True
or
def DeleteUnit(self, strProperty, strUnit):
for property in self.lstProperty:
if property.attrib"name"] == strProperty:
lstUnits = property.getiterator("unit")
for units in lstUnits:
unit = units.getchildren()
if unit[0].text == strUnit:
self.xmlDoc.remove(units) #also tried 'lstUnits.remove(unit)'
self.tree.write(self.xmlFile, "utf-8")
return True
but none of these works. At least the latter one doesn’t give me any error. I think it may be deleting the ‘unit’ from ‘lstUnits’ but how do I save the XML file with the change?
I also found this code on http://effbot.org/zone/element.htm:
parent_map = dict((c, p) for p in tree.getiterator() for c in p)
but I’m not a Python guru yet to understand this… thing.
Could anyone please tell me how to delete a child node in Python? Thank you.