要使生成的 XML 文件头包含 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
,只需在调用 write()
方法时添加 standalone="yes"
参数即可。一下是实现函数:
python
from lxml import etree
def generate_or_update_xml(file_name, root_name, node_paths_and_values):
root = etree.Element(root_name)
# 读取已有文件内容(如果存在),并附加到根节点下
if os.path.exists(file_name):
tree = etree.parse(file_name)
root.extend(tree.getroot().getchildren())
# 处理每个节点路径和值
for path, value in node_paths_and_values:
path_parts = path.split('/')
current_node = root
for part in path_parts[:-1]: # Iterate over all but the last part (the value node)
child = current_node.find(part)
if child is None: # Create the child node if it doesn't exist
child = etree.SubElement(current_node, part)
current_node = child
# Set the value for the last part of the path
current_node.text = value
# 创建 ElementTree 对象,设置编码为 UTF-8,并保存到文件
tree = etree.ElementTree(root)
with open(file_name, 'wb') as f:
tree.write(f, encoding="utf-8", xml_declaration=True, standalone="yes", pretty_print=True)
# 示例用法
generate_or_update_xml(
file_name="output.xml",
root_name="root",
node_paths_and_values=[
("node1/subnode1", "value1"),
("node2/subnode2", "value2"),
("node3/subnode3/subsubnode", "value3")
]
)
在这个版本的函数中,我们添加了 standalone="yes"
参数,确保生成的 XML 文件头包含 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
。确保已安装 lxml
库(可通过 pip install lxml
安装),并使用这个函数生成或更新 XML 文件。