• python读写xml文件 yongqi


    1.python创建xml
    使用xml.etree.ElementTree来操作xml
    创建节点:root = ET.Element('root', attribute),
    其中, attribute是属性字典,需要属性时可以添加

    创建文档:tree = ET.ElementTree(root)
    设置文本值:element.text = 'default'
    设置属性:element.set('age', str(i))
    添加节点:root.append(element)
    写入文档:tree.write('*.xml', encoding='utf-8', xml_declaration=True
    其中,xml_declaration=True表示对xml声明,<?xml version='1.0' encoding='utf-8'?>

    示例:
     

    import xml.etree.ElementTree as ET
    from xml.etree.ElementTree import Element
    root = ET.Element('Root')
    tree = ET.ElementTree(root)
    name = Element("name", {'id': 'id2', 'order': 'order2'})
    name.text = "xiaoming"
    age = Element("age")
    age.text = "12"
    gender = Element("gender")
    gender.text = "男"
    root.append(name)
    root.append(age)
    root.append(gender)
    tree.write("1.xml", encoding='utf-8', xml_declaration=True)
    

      

    结果如下:

    但是此时的xml文件和我们平时常见的格式不太一样,如何转变成标准的格式呢? 

    思路就是在每个节点之后添加"\n\t"

    代码如下:

    import xml.etree.ElementTree as ET
    from xml.etree.ElementTree import Element
     
    def __indent(elem, level=0):
        i = "\n" + level*"\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            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
     
    root = ET.Element('Root')
    tree = ET.ElementTree(root)
    name = Element("name", {'id': 'id2', 'order': 'order2'})
    name.text = "xiaoming"
    age = Element("age")
    age.text = "12"
    gender = Element("gender")
    gender.text = ""
    root.append(name)
    root.append(age)
    root.append(gender)
    __indent(root)
    tree.write("1.xml", encoding='utf-8', xml_declaration=True)
     
     

    结果如下:

    2.python读取/修改xml 

    tree = ET.parse(xml_path) 读取xml文档
    root = tree.getroot() 获取根节点

    示例:读取1.xml的内容,并添加属性,最后写入2.xml

    import xml.etree.ElementTree as ET
    from xml.etree.ElementTree import Element
     
    tree = ET.parse("1.xml")
    root = tree.getroot()
    for child in root:
        print("tag:", child.tag)
        print("tag:", child.text)
        print("attrib:", child.attrib)
        child.set("set:", "设置属性")
    tree.write("2.xml", encoding="utf-8", xml_declaration=True)
     
    """
    tag: name
    tag: xiaoming
    attrib: {'id': 'id2', 'order': 'order2'}
    tag: age
    tag: 12
    attrib: {}
    tag: gender
    tag: 男
    attrib: {}
    """

     THANKS A LOT!

    参考链接:https://blog.csdn.net/hu694028833/article/details/81089959

  • 相关阅读:
    Lua/AHK socket tcp telnet
    Lua wait sleep
    Lua io.open read write seek flush setvbuf append
    stream file 文件 数据流
    AHK通讯 CMD Lua IPC
    零散 Lua/Excel/''/iup
    Windows Program File(x86) 路径 环境变量
    条件正则过滤筛选 V2
    条件正则过滤筛选 V1
    python导包出现的问题
  • 原文地址:https://www.cnblogs.com/gina11/p/16371554.html
Copyright © 2020-2023  润新知