2013-10-31 67 views
1

如何在每次調用此方法時插入或更新匹配條目?在python的elementTree中插入條目到xml

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) 

當我第一次調用該方法時,它應該創建一個新條目。

makeXml("~/Desktop/filterList.mod") 

這第一個版畫<modules><filterList path="~/Desktop/filterList.mod" /></modules>

makeXml("~/Documens/sorter.mod") 

但我想,當同樣的方法執行它應該添加一個新的條目像

<modules> 
<filterList path="~/Desktop/filterList.mod" /> 
<sorter path="~/Documens/sorter.mod" /> 
</modules> 

但它沒有發生,相反,它被覆蓋。

回答

1

這是因爲函數makeXML不是靜態的,所以它不會記得任何其他時間執行的信息。一個簡單的解決方案是將其包裝在一個類中。

更新:我不知道你是如何定義唯一的,但我猜它是通過標籤名稱或路徑。無論哪種方式,它是一個簡單的事情,存儲所有以前看到的項目和檢查。

例如:

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) 

演示:

>>> 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> 
+1

完全正常的,但它會增加一個,如果在同一個條目已經存在。 –

+0

@san我已經更新了我的答案。 – mr2ert