Reputation: 8277
How can I insert or update a matching entry each time this method is called?
def makeXml(path):
root = Element("modules")
tree = ElementTree(root)
childPath = Element(os.path.basename(path).split(".")[0])
childPath.set("path", path)
root.append(childPath)
print etree.tostring(root)
when i call the method first time it should create a new entry.
makeXml("~/Desktop/filterList.mod")
this first one prints<modules><filterList path="~/Desktop/filterList.mod" /></modules>
makeXml("~/Documens/sorter.mod")
but I want when same method execute it should add a new entry like
<modules>
<filterList path="~/Desktop/filterList.mod" />
<sorter path="~/Documens/sorter.mod" />
</modules>
but its not happening, instead it gets overwritten.
Upvotes: 1
Views: 155
Reputation: 5186
This is because the function makeXML
is not static, so it won't remember any information about any of the other times it was executed. A simple solution would be to wrap this in a class.
Update: I'm not sure how you are defining unique, but I'm guessing it is either by tag name or path. Either way it is a simple matter of storing all previously seen items and checking against that.
For example:
class makeXmlContainer:
def __init__(self):
self.root = Element("modules")
self.alreadyseen = []
def makeXml(self, path):
# Uncomment if uniqueness is defined by tag name.
#tagname = os.path.basename(path).split(".")[0]
#if tagname in self.alreadyseen:
# return
#self.alreadyseen.append(tagname)
# Uncomment if uniqueness if defined by path.
#if path in self.alreadyseen:
# return
#self.alreadyseen.append(path)
childPath = Element(os.path.basename(path).split(".")[0])
childPath.set("path", path)
self.root.append(childPath)
print etree.tostring(self.root)
Demo:
>>> foo = makeXmlContainer()
>>> foo.makeXml('foo/bar')
<modules><bar path="foo/bar"/></modules>
>>> foo.makeXml('bing/bang')
<modules><bar path="foo/bar"/><bang path="bing/bang"/></modules>
Upvotes: 1