日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python下的xml创建以及追加信息,删除信息方法

發(fā)布時間:2024/3/13 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。