我有以下代码来编辑 XML
import xml.etree.ElementTree as ET
data = b'<?xml version="1.0" encoding="UTF-8"?><aaaa version="1.0"><zzz>xxxxxx</zzz><bbbb>11111</bbbb></aaaa>'
root = ET.fromstring(data)
# Find the element to update
zzz_element = root.find('zzz')
if zzz_element is not None:
# Update the element's text
zzz_element.text = 'new_value'
# Convert the updated XML back to a string
updated_data = ET.tostring(root, encoding='utf-8', method='xml').decode()
print(updated_data)
该程序的输出是:
<aaaa version="1.0"><zzz>new_value</zzz><bbbb>11111</bbbb></aaaa>
为什么 XML 的 header 是:
<?xml version="1.0" encoding="UTF-8"?>
退学? 我可以编辑 xml,并将其解析为字符串并保留标题吗
您需要通过将
ElementTree.tostring
设置为 xml_declaration
来告知 True
您想要标题,请考虑以下简单示例
import xml.etree.ElementTree as ET
data = b'<?xml version="1.0" encoding="UTF-8"?><thing>abc</thing>'
root = ET.fromstring(data)
root.set("somekey", "somevalue")
updated_data = ET.tostring(root, encoding='utf-8', method='xml', xml_declaration=True).decode()
print(updated_data)
提供输出
<?xml version='1.0' encoding='utf-8'?>
<thing somekey="somevalue">abc</thing>