pthon 写入xml
时间: 2024-09-25 12:01:50 浏览: 44
在Python中,你可以使用`xml.etree.ElementTree`模块来方便地操作XML文件。这个模块提供了一个简单的API,可以用于创建、修改和解析XML文档。以下是写入XML的基本步骤:
1. 导入必要的库:
```python
import xml.etree.ElementTree as ET
```
2. 创建根元素(root element):
```python
root = ET.Element("root")
```
3. 添加子元素:
```python
child1 = ET.SubElement(root, "child1", attrib={"name": "value1"})
child2 = ET.SubElement(root, "child2", {"id": "2"})
```
这里`attrib`参数是一个字典,用于设置元素属性。
4. 设置元素文本内容:
```python
child1.text = "Some text"
child2.text = "Another text"
```
5. 编组XML文档:
```python
tree = ET.ElementTree(root)
```
6. 将XML数据写入文件:
```python
with open('output.xml', 'wb') as f:
tree.write(f, encoding="utf-8", xml_declaration=True)
```
`xml_declaration=True`确保输出的XML文件包含XML声明,`encoding="utf-8"`指定编码格式。
阅读全文
相关推荐
















