python下的xml创建以及追加信息,删除信息方法
生活随笔
收集整理的這篇文章主要介紹了
python下的xml创建以及追加信息,删除信息方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.創(chuàng)建: 創(chuàng)建一個目前沒有的xml文件
import xml.dom.minidom as xdc from xml.dom.minidom import Document from xml.etree import ElementTree as ET from xml.dom.minidom import parse #上面這幾個忘了哪個有用了,干脆都加上來了#創(chuàng)建過程 domTree = Document()#創(chuàng)建xml rootNode = domTree.createElement("frame")#創(chuàng)建跟節(jié)點 rootNode.setAttribute("id", str(i))#根節(jié)點賦值 domTree.appendChild(rootNode)#掛上去customer_node = domTree.createElement("ploygon")#創(chuàng)建子節(jié)點, customer_node.setAttribute("type", "pole") customer_node.setAttribute("point", s) rootNode.appendChild(customer_node)#將他們掛在跟節(jié)點上 with open('sector.xml', 'w') as f:#保存文件為sectordomTree.writexml(f, addindent=' ')創(chuàng)建結(jié)果:因為我這張圖里有兩個多邊形,所以就..
2.追加內(nèi)容: 例如還想多掛幾個叫ploygon的子節(jié)點到sector.xml文件里去。
try:#先嘗試打開sector.xml 看存不存在 存在 就追加domTree = parse('sector.xml')rootNode = domTree.documentElementcustomer_node = domTree.createElement("ploygon")customer_node.setAttribute("type", "pole")#customer_node.setAttribute("point", s)rootNode.appendChild(customer_node)with open('sector.xml', 'w') as f:domTree.writexml(f, addindent=' ') except:#不存在sector.xml文件就創(chuàng)建一個domTree = Document()#創(chuàng)建rootNode = domTree.createElement("frame")rootNode.setAttribute("id", str(i))domTree.appendChild(rootNode)customer_node = domTree.createElement("ploygon")customer_node.setAttribute("type", "pole")rootNode.appendChild(customer_node)with open('sector.xml', 'w') as f:domTree.writexml(f, addindent=' ')運行結(jié)果:
3.刪除內(nèi)容: 例如某個節(jié)點錯了,想給他刪除了
例如有如下xml文件
發(fā)現(xiàn)ploygon id為0這個節(jié)點不想要了。因為它錯誤的。
那么刪除代碼如下:因為多個ploygon 節(jié)點,但是他們有唯一ID號來區(qū)分,那就用id號當索引,去查這個節(jié)點,然后將這個節(jié)點刪除了。
nodelist = rootNode.getElementsByTagName('ploygon') for node in nodelist: #print("node.getAttribute('model') = ", int(node.getAttribute('id')))if '0' == node.getAttribute('id'):print(node.getAttribute('model'))rootNode.removeChild(node)刪除后效果如下:
?
?
總結(jié)
以上是生活随笔為你收集整理的python下的xml创建以及追加信息,删除信息方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: R语言绘制Cleverland点图
- 下一篇: python柱状图挨在一起_Excel图