python使用ElementTree處理xml容易犯錯(cuò)的點(diǎn)&美化xml
- 引言
- 代碼環(huán)境相關(guān)
- 先上代碼
引言
目前因?yàn)樾枰獙懸粋€(gè)tool處理xml文件,對(duì)于面向?yàn)g覽器編程的我來說,迅速打開chrome開始搜索關(guān)鍵字 python xml ,然后打開很多都是各種blog,于是隨便打開了一篇,參考文章主要有如下兩篇:
- Python xml屬性/節(jié)點(diǎn)/文本的增刪改[xml.etree.ElementTree]
- python處理xml文件
這兩篇文章都寫的不錯(cuò),尤其是第一篇大佬寫的是很詳細(xì)了。但是因?yàn)閰⒖剂藘善偌由献约褐傲闵⒌挠洃洠缓笪揖蛯懗鰜砹艘粋€(gè)不work的tool!(黑人問號(hào)臉?為什么就不work了呢?我是按照別人說的去寫的鴨,為什么呢?)在經(jīng)過自己內(nèi)心和行動(dòng)的不斷掙扎之后,我終于弄明白了為什么!
代碼環(huán)境相關(guān)
- os:windows
- ide: vscode
- python: python3.7
- xml文件格式
先上代碼
## 0. Get the root node
import xml.etree.ElementTree as ET
import os
tree = ET.parse("d:\\tool\\input.xml")
root = tree.getroot()
## 1. Find target node
##compare with root.getiterator("Regions")
regions = root.findall("Generation/Regions")
查找指定節(jié)點(diǎn)的代碼需要注意的是
getiterator("regions")
和
findall(Generation/Regions)
,如果在使用findall的時(shí)候沒有指明路徑節(jié)點(diǎn),而是像getiterator那樣直接指定節(jié)點(diǎn)名稱是無法找到regions節(jié)點(diǎn)的(踏了很久的坑)
## 2. Remove one node
for region in regions:
for child in region.getchildren():
if child.get("fileName") == "test_1":
region.remove(child)
## 3. Create and Add one node
attribute_dict={"theme":"test","fileName":"test_2"}
region_node = ET.Element("Region",attribute_dict)
attribute_node = ET.Element("Attribute",{"type":"test"})
region_node.append(attribute_node)
indent(region_node) ##pretty xml, defined in step 4
for region in regions:
region.append(region_node)
刪除和增加節(jié)點(diǎn)的時(shí)候需要找到的是你要?jiǎng)h除節(jié)點(diǎn)的父親節(jié)點(diǎn),然后通過父親節(jié)點(diǎn)進(jìn)行刪除,不能直接找到想要?jiǎng)h除的節(jié)點(diǎn)進(jìn)行刪除,因?yàn)橐坏﹦h除,你就失去了這個(gè)節(jié)點(diǎn)的指向,無法操作成功!(也是一個(gè)坑鴨!)
## 4. pretty xml
def indent(elem, level=0):
i = '\n' + level * ' '
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + ' '
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
這個(gè)是參考了stackoverflow中的答案,因?yàn)镋lementTree這個(gè)庫沒有美化xml的功能,添加新的節(jié)點(diǎn)之后都會(huì)是一行,所以進(jìn)行美化操作!
以上就是操作xml時(shí)候遇到的一些小問題,就給自己做了個(gè)總結(jié)!菜鳥的踩坑之路鴨好漫長,加油!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
