Python實(shí)現(xiàn)的讀取/更改/寫入xml文件操作示例
本文實(shí)例講述了Python實(shí)現(xiàn)的讀取/更改/寫入xml文件操作。分享給大家供大家參考,具體如下:
原始文檔內(nèi)容(test.xml):
<?xml version="1.0" encoding="UTF-8"?> <framework> <processers> <processer name="AProcesser" file="lib64/A.so" path="/tmp"> </processer> <processer name="BProcesser" file="lib64/B.so" value="fordelete"> </processer> <processer name="BProcesser" file="lib64/B.so2222222"/> <services> <service name="search" prefix="/bin/search?" output_formatter="OutPutFormatter:service_inc"> <chain sequency="chain1"/> <chain sequency="chain2"></chain> </service> <service name="update" prefix="/bin/update?"> <chain sequency="chain3" value="fordelete"/> </service> </services> </processers> </framework>
Python操作xml代碼:
# -*- coding:utf-8 -*- ''' Created on 2018年8月30日 @author: Administrator ''' from xml.etree.ElementTree import ElementTree,Element def read_xml(in_path): '''''讀取并解析xml文件 in_path: xml路徑 return: ElementTree''' tree = ElementTree() tree.parse(in_path) return tree def write_xml(tree, out_path): '''''將xml文件寫出 tree: xml樹 out_path: 寫出路徑''' tree.write(out_path, encoding="utf-8",xml_declaration=True) def if_match(node, kv_map): '''''判斷某個(gè)節(jié)點(diǎn)是否包含所有傳入?yún)?shù)屬性 node: 節(jié)點(diǎn) kv_map: 屬性及屬性值組成的map''' for key in kv_map: if node.get(key) != kv_map.get(key): return False return True #---------------search ----- def find_nodes(tree, path): '''''查找某個(gè)路徑匹配的所有節(jié)點(diǎn) tree: xml樹 path: 節(jié)點(diǎn)路徑''' return tree.findall(path) def get_node_by_keyvalue(nodelist, kv_map): '''''根據(jù)屬性及屬性值定位符合的節(jié)點(diǎn),返回節(jié)點(diǎn) nodelist: 節(jié)點(diǎn)列表 kv_map: 匹配屬性及屬性值map''' result_nodes = [] for node in nodelist: if if_match(node, kv_map): result_nodes.append(node) return result_nodes #---------------change ----- def change_node_properties(nodelist, kv_map, is_delete=False): '''''修改/增加 /刪除 節(jié)點(diǎn)的屬性及屬性值 nodelist: 節(jié)點(diǎn)列表 kv_map:屬性及屬性值map''' for node in nodelist: for key in kv_map: if is_delete: if key in node.attrib: del node.attrib[key] else: node.set(key, kv_map.get(key)) def change_node_text(nodelist, text, is_add=False, is_delete=False): '''''改變/增加/刪除一個(gè)節(jié)點(diǎn)的文本 nodelist:節(jié)點(diǎn)列表 text : 更新后的文本''' for node in nodelist: if is_add: node.text += text elif is_delete: node.text = "" else: node.text = text def create_node(tag, property_map, content): '''''新造一個(gè)節(jié)點(diǎn) tag:節(jié)點(diǎn)標(biāo)簽 property_map:屬性及屬性值map content: 節(jié)點(diǎn)閉合標(biāo)簽里的文本內(nèi)容 return 新節(jié)點(diǎn)''' element = Element(tag, property_map) element.text = content return element def add_child_node(nodelist, element): '''''給一個(gè)節(jié)點(diǎn)添加子節(jié)點(diǎn) nodelist: 節(jié)點(diǎn)列表 element: 子節(jié)點(diǎn)''' for node in nodelist: node.append(element) def del_node_by_tagkeyvalue(nodelist, tag, kv_map): '''''同過屬性及屬性值定位一個(gè)節(jié)點(diǎn),并刪除之 nodelist: 父節(jié)點(diǎn)列表 tag:子節(jié)點(diǎn)標(biāo)簽 kv_map: 屬性及屬性值列表''' for parent_node in nodelist: children = parent_node.getchildren() for child in children: if child.tag == tag and if_match(child, kv_map): parent_node.remove(child) if __name__ == "__main__": #1. 讀取xml文件 tree = read_xml("D://test.xml") #2. 屬性修改 #A. 找到父節(jié)點(diǎn) nodes = find_nodes(tree, "processers/processer") #B. 通過屬性準(zhǔn)確定位子節(jié)點(diǎn) result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"}) #C. 修改節(jié)點(diǎn)屬性 change_node_properties(result_nodes, {"age": "1"}) #D. 刪除節(jié)點(diǎn)屬性 change_node_properties(result_nodes, {"value":""}, True) #3. 節(jié)點(diǎn)修改 #A.新建節(jié)點(diǎn) a = create_node("person", {"age":"15","money":"200000"}, "this is the firest content") #B.插入到父節(jié)點(diǎn)之下 add_child_node(result_nodes, a) #4. 刪除節(jié)點(diǎn) #定位父節(jié)點(diǎn) del_parent_nodes = find_nodes(tree, "processers/services/service") #準(zhǔn)確定位子節(jié)點(diǎn)并刪除之 target_del_node = del_node_by_tagkeyvalue(del_parent_nodes, "chain", {"sequency" : "chain1"}) #5. 修改節(jié)點(diǎn)文本 #定位節(jié)點(diǎn) text_nodes = get_node_by_keyvalue(find_nodes(tree, "processers/services/service/chain"), {"sequency":"chain3"}) change_node_text(text_nodes, "new text") #6. 輸出到結(jié)果文件 write_xml(tree, "D://xiugai.xml")
更改之后的內(nèi)容(xiugai.xml):
<?xml version='1.0' encoding='utf-8'?> <framework> <processers> <processer file="lib64/A.so" name="AProcesser" path="/tmp"> </processer> <processer age="1" file="lib64/B.so" name="BProcesser"> <person age="15" money="200000">this is the firest content</person></processer> <processer age="1" file="lib64/B.so2222222" name="BProcesser"><person age="15" money="200000">this is the firest content</person></processer> <services> <service name="search" output_formatter="OutPutFormatter:service_inc" prefix="/bin/search?"> <chain sequency="chain2" /> </service> <service name="update" prefix="/bin/update?"> <chain sequency="chain3" value="fordelete">new text</chain> </service> </services> </processers> </framework>
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作xml數(shù)據(jù)技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python中的并發(fā)編程asyncio庫(kù)入門使用
這篇文章主要為大家介紹了Python中的并發(fā)編程asyncio庫(kù)入門的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05Python?Pandas多種添加行列數(shù)據(jù)方法總結(jié)
在進(jìn)行數(shù)據(jù)分析時(shí)經(jīng)常需要按照一定條件創(chuàng)建新的數(shù)據(jù)列,然后進(jìn)行進(jìn)一步分析,下面這篇文章主要給大家介紹了關(guān)于Python?Pandas多種添加行列數(shù)據(jù)方法的相關(guān)資料,需要的朋友可以參考下2022-07-07django 刪除數(shù)據(jù)庫(kù)表后重新同步的方法
今天小編就為大家分享一篇django 刪除數(shù)據(jù)庫(kù)表后重新同步的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05Pytorch中關(guān)于nn.Conv2d()參數(shù)的使用
這篇文章主要介紹了Pytorch中關(guān)于nn.Conv2d()參數(shù)的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06代碼總結(jié)Python2 和 Python3 字符串的區(qū)別
在本篇文章里小編給大家整理的是一篇關(guān)于Python2 和 Python3 字符串的區(qū)別以及實(shí)例代碼,需要的朋友們學(xué)習(xí)下。2020-01-01python正則表達(dá)式完成車牌號(hào)檢驗(yàn)的代碼實(shí)例
這篇文章主要給大家介紹了關(guān)于python正則表達(dá)式完成車牌號(hào)檢驗(yàn)的相關(guān)資料,在Python中正則表達(dá)式是一種用于匹配和操作字符串的強(qiáng)大工具,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02