python自动生成xml文件
时间: 2023-09-15 10:23:14 浏览: 43
Python可以使用内置的xml模块来生成xml文件。下面是一个示例代码,它将创建一个名为“example.xml”的XML文件,并在其中添加一些元素和属性:
```Python
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element("example")
# 添加子元素
child1 = ET.SubElement(root, "child1")
child1.text = "This is child 1."
# 添加属性
child2 = ET.SubElement(root, "child2", attrib={"name": "child2"})
child2.text = "This is child 2."
# 创建XML树
tree = ET.ElementTree(root)
# 将XML树写入文件
tree.write("example.xml", encoding="utf-8", xml_declaration=True)
```
运行上面的代码后,将创建一个名为“example.xml”的XML文件,其内容如下所示:
```XML
<?xml version='1.0' encoding='utf-8'?>
<example>
<child1>This is child 1.</child1>
<child2 name="child2">This is child 2.</child2>
</example>
```
请注意,我们使用`xml_declaration=True`参数来包含XML声明。此外,我们还可以使用`ET.tostring()`方法将XML树转换为字符串,并将其打印到控制台上,如下所示:
```Python
xml_string = ET.tostring(root, encoding="utf-8", method="xml")
print(xml_string.decode())
```
这将打印XML树的字符串表示形式,如下所示:
```XML
<example>
<child1>This is child 1.</child1>
<child2 name="child2">This is child 2.</child2>
</example>
```
这是为了在控制台上查看XML树而不是将其写入文件。