我想使用 Python 将带有子元素的元素添加到我的 xml 文件中。但更改文件后,元素和子元素看起来像一条线,而不是像 xml 树。
我这样做:
tree = ET.parse('existing_file.xml')
root = tree.getroot()
new_object = ET.SubElement(root, 'object')
name = ET.SubElement(new_object, 'name')
name.text = 'car'
color = ET.SubElement(new_object, 'color')
color.text = 'Red'
new_tree = ET.ElementTree(root)
new_tree.write('new_file.xml')
但是在此之后我得到了没有这样结构的文件:
<object><name>car</name><color>red</color></object>
但是我需要这个:
<object>
<name>car</name>
<color>red</color>
</object>
我做错了什么?
使用
new_tree = ET.ElementTree(root)
ET.indent(new_tree)
new_tree.write('new_file.xml', xml_declaration=True, short_empty_elements=True)
或使用
xml.dom.minidom.parseString
new_object = ET.SubElement(root, 'object')
name = ET.SubElement(new_object, 'name')
name.text = 'car'
color = ET.SubElement(new_object, 'color')
color.text = 'Red'
# Convert the ElementTree to a string with indentation
xml_string = ET.tostring(root, encoding='unicode')
# Use minidom to format the XML string
dom = xml.dom.minidom.parseString(xml_string)
formatted_xml = dom.toprettyxml()
# Write the formatted XML to a new file
with open('new_file.xml', 'w') as f:
f.write(formatted_xml)
<?xml version="1.0" ?>
<object>
<name>car</name>
<color>red</color>
<object>
<name>car</name>
<color>Red</color>
</object>
</object>