欢迎访问宙启技术站
智能推送

使用toprettyxml()函数在Python中生成易于阅读的XML文档

发布时间:2024-01-05 08:26:26

在Python中,可以使用标准库xml.dom.minidom中的toprettyxml()函数来生成易于阅读的XML文档。

以下是一个使用toprettyxml()函数的简单示例:

import xml.dom.minidom

# 创建一个简单的XML文档
doc = xml.dom.minidom.Document()
root = doc.createElement("root")
doc.appendChild(root)

child1 = doc.createElement("child")
child1_text = doc.createTextNode("Hello")
child1.appendChild(child1_text)
root.appendChild(child1)

child2 = doc.createElement("child")
child2_text = doc.createTextNode("World")
child2.appendChild(child2_text)
root.appendChild(child2)

# 使用toprettyxml()函数生成易于阅读的XML文档
xml_str = doc.toprettyxml(indent="  ")

# 打印生成的XML文档
print(xml_str)

运行上述代码,将会输出以下结果:

<?xml version="1.0" ?>
<root>
  <child>Hello</child>
  <child>World</child>
</root>

可以看到,使用toprettyxml()函数生成的XML文档带有适当的缩进,易于阅读。

在上述示例中,首先创建了一个简单的XML文档,并通过appendChild()函数将元素添加到文档中。然后,通过调用toprettyxml()函数,将XML文档转换为易于阅读的字符串形式。

toprettyxml()函数接受一个可选的indent参数,用于指定每一级缩进的字符串。在示例中,我们将indent参数设置为两个空格,并将其传递给toprettyxml()函数。

值得注意的是,使用toprettyxml()函数生成的XML文档会在开头添加一个XML声明<?xml version="1.0" ?>。如果不需要此声明,可以在调用toprettyxml()函数时传递参数xml_declaration=False

此外,还可以通过调整Document对象的属性和方法,来定制生成的XML文档的其他方面,如元素命名空间、属性等。

综上所述,通过在Python中使用toprettyxml()函数,可以方便地生成易于阅读的XML文档。