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

 更新时间:2018年08月30日 11:33:35   作者:飘的心  
这篇文章主要介绍了Python实现的读取/更改/写入xml文件操作,涉及Python针对xml文件的读取、节点操作、写入等相关实现技巧,需要的朋友可以参考下

本文实例讲述了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>

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
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

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

  • Python队列Queue实现详解

    Python队列Queue实现详解

    这篇文章主要介绍了Python队列Queue实现详解,队列是一种列表,队列用于存储按顺序排列的数据,队列是一种先进先出的数据结构,不同的是队列只能在队尾插入元素,在队首删除元素,需要的朋友可以参考下
    2023-07-07
  • Python读取图片的方法详解

    Python读取图片的方法详解

    这篇文章主要为大家详细介绍了Python中读取图片的实现方法,文中的示例代码简洁易懂,具有一定的参考价值,需要的小伙伴可以跟随小编一起学习一下
    2023-08-08
  • 详解pytorch tensor和ndarray转换相关总结

    详解pytorch tensor和ndarray转换相关总结

    这篇文章主要介绍了详解pytorch tensor和ndarray转换相关总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Python功能键的读取方法

    Python功能键的读取方法

    这篇文章主要介绍了Python功能键的读取方法,涉及Python键盘事件的相关操作技巧,需要的朋友可以参考下
    2015-05-05
  • 浅谈Selenium 控制浏览器的常用方法

    浅谈Selenium 控制浏览器的常用方法

    这篇文章主要介绍了浅谈Selenium 控制浏览器的常用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Python xlwt工具使用详解,生成excel栏位宽度可自适应内容长度

    Python xlwt工具使用详解,生成excel栏位宽度可自适应内容长度

    这篇文章主要介绍了Python xlwt工具使用详解,生成excel栏位宽度可自适应内容长度,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • Python使用CRC32实现校验文件

    Python使用CRC32实现校验文件

    CRC文件校验是一种用于验证文件完整性的方法,通过计算文件的CRC值并与预先计算的CRC校验值进行比较,来判断文件是否发生变化,本文我们就来介绍一下Python如何利用CRC32实现校验文件吧
    2023-10-10
  • python 同时读取多个文件的例子

    python 同时读取多个文件的例子

    今天小编就为大家分享一篇python 同时读取多个文件的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Python 列表推导式与字典推导式的实现

    Python 列表推导式与字典推导式的实现

    本文主要介绍了Python 列表推导式与字典推导式的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • 代码实例讲解python3的编码问题

    代码实例讲解python3的编码问题

    在本篇内容里小编给各位分享了关于python3的编码问题以及相关实例代码,有需要的朋友们参考一下。
    2019-07-07

最新评论