Python xml属性间怎么换行
时间: 2023-11-19 13:13:03 浏览: 59
在 Python 中,可以使用 `minidom` 模块来创建和操作 XML 文档。要在 XML 属性之间换行,可以使用 `Node.toprettyxml()` 方法的 `indent` 和 `newl` 参数。
以下是一个示例代码:
```python
import xml.dom.minidom
# 创建 XML 文档
doc = xml.dom.minidom.Document()
root = doc.createElement('root')
doc.appendChild(root)
# 添加一个元素及其属性
elem = doc.createElement('elem')
elem.setAttribute('attr1', 'value1')
elem.setAttribute('attr2', 'value2')
# 设置 toprettyxml() 方法的参数
xml_str = doc.toprettyxml(indent='\t', newl='\n')
# 输出 XML 字符串
print(xml_str)
```
在上面的示例中,我们将 `indent` 参数设置为 `\t`,表示使用制表符缩进 XML 元素。将 `newl` 参数设置为 `\n`,表示在 XML 属性之间添加换行符。输出的 XML 字符串如下:
```
<?xml version="1.0" ?>
<root>
<elem attr1="value1"
attr2="value2"/>
</root>
```
其中,`attr1` 和 `attr2` 之间有一个换行符。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)