2010-06-04 319 views
4

我想知道是否最好通過打開文件添加一個元素,搜索'good place'並添加包含xml代碼的字符串。 或者使用一些庫...我不知道。我知道如何從xml中獲取節點和屬性,例如lxml,但最簡單和最好的方式是什麼?使用python添加xml節點到xml文件

回答

4

你可以使用lxml.etree.Element使XML節點(S),並用appendinsert將其連接到XML文檔:

data='''\ 
<root> 
<node1> 
    <node2 a1="x1"> ... </node2> 
    <node2 a1="x2"> ... </node2> 
    <node2 a1="x1"> ... </node2> 
</node1> 
</root> 
''' 
doc = lxml.etree.XML(data) 
e=doc.find('node1') 
child = lxml.etree.Element("node3",attrib={'a1':'x3'}) 
child.text='...' 
e.insert(1,child) 
print(lxml.etree.tostring(doc)) 

產量:

<root> 
    <node1> 
     <node2 a1="x1"> ... </node2> 
     <node3 a1="x3">...</node3><node2 a1="x2"> ... </node2> 
     <node2 a1="x1"> ... </node2> 
    </node1> 
    </root> 
+0

謝謝,LXML非常簡單並澄清。 – matiit 2010-06-05 10:30:39

1

將節點添加到XML文檔中最安全的方法是將其加載到DOM中,以編程方式添加節點並再次寫出。有幾個Python XML庫。我已經使用了minidom,但我沒有理由特別推薦它。