python,ElementTree插入元素后换行
时间: 2024-05-08 17:20:01 浏览: 18
可以使用方法`ElementTree.SubElement()`添加元素,并使用`ElementTree.tostring()`方法将其转换为字符串。如果想要避免在元素间出现换行,可以使用`minidom`模块来格式化XML字符串,代码如下:
```python
import xml.etree.ElementTree as ET
from xml.dom import minidom
# 创建XML文件
root = ET.Element("root")
child1 = ET.Element("child1")
child2 = ET.Element("child2")
root.append(child1)
root.append(child2)
# 添加新元素
new_element = ET.Element("new_element")
child1.append(new_element)
# 转换为字符串
xml_str = ET.tostring(root, encoding="unicode")
# 格式化XML,避免换行
parsed_xml = minidom.parseString(xml_str)
formatted_xml = parsed_xml.toprettyxml()
print(formatted_xml)
```
相关问题
python,ElementTree插入元素时换行
如果需要在使用ElementTree插入元素时强制换行,则可以使用以下代码:
```python
from xml.etree.ElementTree import Element, SubElement, tostring
root = Element('root')
child1 = SubElement(root, 'child1')
child1.text = 'Child 1 text'
child2 = SubElement(root, 'child2')
child2.text = 'Child 2 text'
# Insert a newline character before the child2 element
root.insert(1, Element('\n'))
print(tostring(root))
```
这会将一个换行符元素插入在child1和child2之间,输出结果如下:
```
<root><child1>Child 1 text</child1>
\n<child2>Child 2 text</child2></root>
```
python,ElementTree插入子级后进行换行
你可以使用ElementTree的tostring()方法中的pretty_print参数来自动进行换行。例如:
```python
import xml.etree.ElementTree as ET
# 创建XML根元素
root = ET.Element("root")
# 插入子元素
child1 = ET.SubElement(root, "child1")
child1.text = "This is child1"
child2 = ET.SubElement(root, "child2")
child2.text = "This is child2"
# 使用tostring()方法输出XML字符串,并设置pretty_print参数为True
xml_string = ET.tostring(root, encoding="unicode", method="xml", pretty_print=True)
print(xml_string)
```
输出结果为:
```xml
<root>
<child1>This is child1</child1>
<child2>This is child2</child2>
</root>
```