python生成xml文件
时间: 2023-08-20 08:09:57 浏览: 67
要使用Python生成XML文件,可以使用xml.dom.minidom模块或xml.etree.ElementTree模块。
在xml.dom.minidom模块中,可以使用Document类来创建XML文档对象,然后使用createElement()、appendChild()和createTextNode()等方法来创建元素和文本节点,并将它们添加到文档中。最后,可以使用toprettyxml()方法将文档格式化为字符串或将其写入文件。以下是一个使用xml.dom.minidom模块创建XML文件的示例代码:
```python
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement("root")
doc.appendChild(root)
element = doc.createElement("element")
text = doc.createTextNode("This is a test!")
element.appendChild(text)
root.appendChild(element)
xml_str = doc.toprettyxml(indent=" ")
with open("output.xml", "w") as f:
f.write(xml_str)
```
在xml.etree.ElementTree模块中,可以使用ElementTree类来创建XML文档对象,然后使用Element()和SubElement()等方法来创建元素,并使用text属性设置元素的文本内容。最后,可以使用ElementTree的write()方法将文档写入文件。以下是一个使用xml.etree.ElementTree模块创建XML文件的示例代码:
```python
import xml.etree.ElementTree as ET
root = ET.Element("root")
element = ET.SubElement(root, "element")
element.text = "This is a test!"
tree = ET.ElementTree(root)
tree.write("output.xml")
```
以上是两种常用的方法来生成XML文件的示例代码。你可以根据自己的需求选择其中一种方法来使用。
#### 引用[.reference_title]
- *1* [怎么用python创建文件-如何用Python创建生成xml文档文件的方法](https://blog.csdn.net/weixin_37988176/article/details/109417617)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [Python学习(十四):Python如何创建一个xml文件](https://blog.csdn.net/weixin_43580890/article/details/129343510)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)