在XML文件中写入并保存数据通常涉及以下几个步骤:
XML(eXtensible Markup Language)是一种标记语言,用于存储和传输数据。它使用标签来定义元素,类似于HTML,但XML的设计目的是传输和存储数据,而不是显示数据。
以下是使用Python语言写入并保存XML文件的示例:
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element("root")
# 添加子元素
child1 = ET.SubElement(root, "child1")
child1.text = "This is child1"
child2 = ET.SubElement(root, "child2")
child2.text = "This is child2"
# 创建ElementTree对象
tree = ET.ElementTree(root)
# 写入文件
tree.write("example.xml")
ET.Element("root")
创建XML的根元素。ET.SubElement(root, "child1")
添加子元素,并设置其文本内容。ElementTree
对象中。tree.write("example.xml")
将XML数据写入文件。原因:默认情况下,ElementTree
可能使用ASCII编码,导致非ASCII字符无法正确保存。
解决方法:指定编码为UTF-8。
tree.write("example.xml", encoding="utf-8", xml_declaration=True)
原因:默认写入的XML文件可能没有良好的格式,难以阅读。
解决方法:使用xml.dom.minidom
进行格式化。
import xml.dom.minidom as minidom
def prettify(elem):
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
pretty_xml = prettify(root)
with open("example_pretty.xml", "w", encoding="utf-8") as f:
f.write(pretty_xml)
通过上述步骤和方法,你可以有效地在XML文件中写入并保存数据,同时解决常见的编码和格式化问题。
领取专属 10元无门槛券
手把手带您无忧上云