python读写xml文件

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: {}
"""
2.xml的内容如下:


————————————————
版权声明:本文为CSDN博主「Jingle-stu」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40006760/article/details/119251626

posted @ 2022-12-29 17:44  阿风小子  阅读(1200)  评论(0编辑  收藏  举报