Python实现的读取/更改/写入xml文件操作示例


Posted in Python onAugust 30, 2018

本文实例讲述了Python实现的读取/更改/写入xml文件操作。分享给大家供大家参考,具体如下:

原始文档内容(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):
  '''''判断某个节点是否包含所有传入参数属性
    node: 节点
    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):
  '''''查找某个路径匹配的所有节点
    tree: xml树
    path: 节点路径'''
  return tree.findall(path)
def get_node_by_keyvalue(nodelist, kv_map):
  '''''根据属性及属性值定位符合的节点,返回节点
    nodelist: 节点列表
    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):
  '''''修改/增加 /删除 节点的属性及属性值
    nodelist: 节点列表
    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):
  '''''改变/增加/删除一个节点的文本
    nodelist:节点列表
    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):
  '''''新造一个节点
    tag:节点标签
    property_map:属性及属性值map
    content: 节点闭合标签里的文本内容
    return 新节点'''
  element = Element(tag, property_map)
  element.text = content
  return element
def add_child_node(nodelist, element):
  '''''给一个节点添加子节点
    nodelist: 节点列表
    element: 子节点'''
  for node in nodelist:
    node.append(element)
def del_node_by_tagkeyvalue(nodelist, tag, kv_map):
  '''''同过属性及属性值定位一个节点,并删除之
    nodelist: 父节点列表
    tag:子节点标签
    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. 找到父节点
  nodes = find_nodes(tree, "processers/processer")
  #B. 通过属性准确定位子节点
  result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"})
  #C. 修改节点属性
  change_node_properties(result_nodes, {"age": "1"})
  #D. 删除节点属性
  change_node_properties(result_nodes, {"value":""}, True)
  #3. 节点修改
  #A.新建节点
  a = create_node("person", {"age":"15","money":"200000"}, "this is the firest content")
  #B.插入到父节点之下
  add_child_node(result_nodes, a)
  #4. 删除节点
  #定位父节点
  del_parent_nodes = find_nodes(tree, "processers/services/service")
  #准确定位子节点并删除之
  target_del_node = del_node_by_tagkeyvalue(del_parent_nodes, "chain", {"sequency" : "chain1"})
  #5. 修改节点文本
  #定位节点
  text_nodes = get_node_by_keyvalue(find_nodes(tree, "processers/services/service/chain"), {"sequency":"chain3"})
  change_node_text(text_nodes, "new text")
  #6. 输出到结果文件
  write_xml(tree, "D://xiugai.xml")

更改之后的内容(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>
Python 相关文章推荐
python中使用OpenCV进行人脸检测的例子
Apr 18 Python
python实现读取命令行参数的方法
May 22 Python
利用Python获取赶集网招聘信息前篇
Apr 18 Python
使用Python对SQLite数据库操作
Apr 06 Python
Python MD5加密实例详解
Aug 02 Python
Python定时器实例代码
Nov 01 Python
pandas string转dataframe的方法
Apr 11 Python
对pandas数据判断是否为NaN值的方法详解
Nov 06 Python
python爬虫数据保存到mongoDB的实例方法
Jul 28 Python
python复合条件下的字典排序
Dec 18 Python
Python实现粒子群算法的示例
Feb 14 Python
pytest实现多进程与多线程运行超好用的插件
Jul 15 Python
python实现录音小程序
Oct 26 #Python
Python图像处理之简单画板实现方法示例
Aug 30 #Python
浅析python中numpy包中的argsort函数的使用
Aug 30 #Python
浅析python3中的os.path.dirname(__file__)的使用
Aug 30 #Python
python语音识别实践之百度语音API
Aug 30 #Python
python调用百度语音识别实现大音频文件语音识别功能
Aug 30 #Python
python的中异常处理机制
Aug 30 #Python
You might like
长波知识介绍
2021/03/01 无线电
PHP similar_text 字符串的相似性比较函数
2010/05/26 PHP
JpGraph php柱状图使用介绍
2011/08/23 PHP
七款最流行的PHP本地服务器分享
2013/02/19 PHP
将FCKeditor导入PHP+SMARTY的实现方法
2015/01/15 PHP
PHP中的命名空间详细介绍
2015/07/02 PHP
PHP常见加密函数用法示例【crypt与md5】
2019/01/27 PHP
PHP与Web页面的交互示例详解二
2020/08/04 PHP
js 数据类型转换总结笔记
2011/01/17 Javascript
JS自定义功能函数实现动态添加网址参数修改网址参数值
2013/08/02 Javascript
javascript的propertyIsEnumerable()方法使用介绍
2014/04/09 Javascript
js获取鼠标点击的对象,点击另一个按钮删除该对象的实现代码
2016/05/13 Javascript
JS短信验证码倒计时功能的实现(没有验证码,只有倒计时)
2016/10/27 Javascript
Jquery on绑定的事件 触发多次实例代码
2016/12/08 Javascript
jQuery分页插件jquery.pagination.js使用方法解析
2017/02/09 Javascript
jQuery、layer实现弹出层的打开、关闭功能
2017/06/28 jQuery
详解vue渲染从后台获取的json数据
2017/07/06 Javascript
Vue中div contenteditable 的光标定位方法
2018/08/25 Javascript
javascript实现文本框标签验证的实例代码
2018/10/14 Javascript
深入浅析vue-cli@3.0 使用及配置说明
2019/05/08 Javascript
使用Python编写vim插件的简单示例
2015/04/17 Python
深入浅析Python字符编码
2015/11/12 Python
利用Python开发微信支付的注意事项
2016/08/19 Python
Python实现读取Properties配置文件的方法
2018/03/29 Python
Python字典遍历操作实例小结
2019/03/05 Python
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
2019/08/28 Python
python多进程并行代码实例
2019/09/30 Python
PyCharm中Matplotlib绘图不能显示UI效果的问题解决
2020/03/12 Python
Python实现寻找回文数字过程解析
2020/06/09 Python
新秀丽拉杆箱美国官方网站:Samsonite美国
2016/07/25 全球购物
Koral官方网站:女性时尚运动服
2019/04/10 全球购物
Jowissa官方网站:瑞士制造的手表,优雅简约的设计
2020/07/29 全球购物
2014小学语文教学工作总结
2014/12/17 职场文书
意向协议书
2015/01/27 职场文书
python实现大文本文件分割成多个小文件
2021/04/20 Python
Java代码规范与质量检测插件SonarLint的使用
2022/08/05 Java/Android