如何用Python的xmltodict库正确生成带属性的XML根标签
问题描述
需要生成的正确XML如下:
<?xml version="1.0" encoding="utf-8"?> <fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <foo> <bar>1</bar> </foo> </fooList>
使用Python的xmltodict库从字典生成XML时,出现闭合标签错误:根标签fooList的闭合标签错误地复制了所有属性,而非仅输出</fooList>。错误输出示例:
<?xml version="1.0" encoding="utf-8"?> <fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <foo> <bar>1</bar> </foo> </fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
当前使用的Python代码:
entry = { '<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance': { "foo": { "bar": 1, } } } xml = xmltodict.unparse(entry, pretty=True)
请问如何修正代码以生成正确的XML?
解决方案
问题出在你错误地将根标签的完整属性字符串直接作为字典的键,xmltodict库无法识别这种格式,导致闭合标签异常。
正确的写法是:将根元素名称作为字典键,元素的属性以@前缀的键来定义,子元素直接作为同级键值对。修正后的代码如下:
import xmltodict entry = { "fooList": { "@action": "add", "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "foo": { "bar": 1 } } } xml = xmltodict.unparse(entry, pretty=True) print(xml)
运行这段代码后,就能生成符合要求的XML,根标签的闭合标签会正确输出为</fooList>。
内容的提问来源于stack exchange,提问作者python_help
相关产品推荐
相关产品推荐

