You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中xml.etree.ElementTree添加xsi属性时语法错误求助

解决Python xml.etree.ElementTree添加带命名空间前缀属性的语法错误

你遇到的语法错误原因很直接——Python不允许关键字参数名称包含冒号,而你要添加的xsi:noNamespaceSchemaLocation属性名里正好有冒号,直接把它作为xml.Element的关键字参数传参,自然会触发SyntaxError。

下面给你两种可行的解决办法:

方法1:通过属性字典传递属性

直接用字典定义所有属性,字典的键可以包含冒号,同时别忘了注册xsi对应的标准命名空间URI,这样生成的XML才会符合规范:

import xml.etree.ElementTree as xml

# 注册xsi命名空间前缀,避免输出时被自动替换成ns0这类无意义前缀
xml.register_namespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance')
# 用字典传递带冒号的属性
root = xml.Element('Tests', {'xsi:noNamespaceSchemaLocation': 'anyURI'})

方法2:使用set()方法动态添加属性

如果是先创建元素再补充属性,用set()方法会更灵活,适合后续动态调整属性的场景:

import xml.etree.ElementTree as xml

xml.register_namespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root = xml.Element('Tests')
# 调用set方法添加带命名空间前缀的属性
root.set('xsi:noNamespaceSchemaLocation', 'anyURI')

验证生成的XML

如果要查看最终的XML内容,可以用ElementTree.tostring方法输出:

print(xml.tostring(root, encoding='utf-8').decode('utf-8'))

会得到符合预期的结果:

<Tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="anyURI" />

内容的提问来源于stack exchange,提问作者Dominik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:58:25