要在生成的 XML 根节点上添加 xmlns:xs="http://www.w3.org/2001/XMLSchema"
属性,可以在创建根节点时直接指定该属性。以下是修改后的函数:
python
from lxml import etree
def generate_or_update_xml(file_name, root_name, node_paths_and_values):
root = etree.Element(root_name, xmlns_xs="http://www.w3.org/2001/XMLSchema")
# 读取已有文件内容(如果存在),并附加到根节点下
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="EBD",
node_paths_and_values=[
("node1/subnode1", "value1"),
("node2/subnode2", "value2"),
("node3/subnode3/subsubnode", "value3")
]
)
在这个版本的函数中,我们创建根节点时指定了 xmlns_xs="http://www.w3.org/2001/XMLSchema"
属性。这将使生成的 XML 根节点包含 <EBD xmlns:xs="http://www.w3.org/2001/XMLSchema">
。确保已安装 lxml
库(可通过 pip install lxml
安装),并使用这个函数生成或更新 XML 文件。