如何让xmltodict.unparse输出包含命名空间声明?
使用xmltodict生成带命名空间声明的XML
问题描述
我用xmltodict将Python字典转换为XML,希望输出结果中包含命名空间声明,但当前实现未达到预期效果。
当前代码
xml_dict = { "http://namespace.org:workflow": {"action-list": "..."} } namespaces = {"http://namespace.org": "ws"} xml = xmltodict.unparse(xml_dict, namespaces=namespaces, pretty=True, short_empty_elements=True, full_document=False)
当前输出
<ws:workflow> <action-list>...</action-list> </ws:workflow>
期望输出
<ws:workflow xmlns:ws="http://namespace.org"> <action-list>...</action-list> </ws:workflow>
我注意到unparse的preprocessor参数可能有用,但它没有官方文档说明,想问下有没有简便的解决方案?
解决方案
方法1:直接在字典中添加命名空间属性
这是最直观的方式,无需额外函数,直接在根元素的字典里手动注入命名空间声明属性:
xml_dict = { "{http://namespace.org}workflow": {"@xmlns:ws": "http://namespace.org", "action-list": "..."} } namespaces = {"http://namespace.org": "ws"} xml = xmltodict.unparse(xml_dict, namespaces=namespaces, pretty=True, short_empty_elements=True, full_document=False)
方法2:利用preprocessor参数批量处理
如果需要对多个元素统一处理,可以借助preprocessor参数在生成XML前修改元素属性。这个参数允许你在每个元素被解析前拦截并修改对应的键值对:
def inject_namespace(path, key, value): # 仅处理根元素(path为空列表时) if not path and key == "{http://namespace.org}workflow": if isinstance(value, dict) and "@xmlns:ws" not in value: value["@xmlns:ws"] = "http://namespace.org" return key, value xml_dict = { "{http://namespace.org}workflow": {"action-list": "..."} } namespaces = {"http://namespace.org": "ws"} xml = xmltodict.unparse( xml_dict, namespaces=namespaces, pretty=True, short_empty_elements=True, full_document=False, preprocessor=inject_namespace )
关键注意点
- 字典中的命名空间格式必须写成
{命名空间URL}元素名,而非之前的命名空间URL:元素名,这样xmltodict才能正确关联命名空间前缀。 - 当设置
full_document=False时,xmltodict不会自动为根元素添加命名空间声明,因此需要手动注入属性。
内容的提问来源于stack exchange,提问作者Arpad Horvath -- Слава Україні
相关产品推荐
相关产品推荐

