etree.ElementTree使用特殊字符添加标记属性

时间:2018-05-16 11:44:50

标签: xml python-3.x xml-parsing

我希望使用属性xsi:noNamespaceSchemaLocation生成Element。

<Test name="Name" xsi:noNamespaceSchemaLocation="anyURI"></a>

我的python代码

import xml.etree.ElementTree as xml
root = xml.Element('Tests', xsi:noNamespaceSchemaLocation="anyURI")

当我尝试运行python文件时。得到错误

  

文件“... / xml-generator.py”,第4行       root = xml.Element('Tests',xsi:noNamespaceSchemaLocation =“anyURI”)                                      ^ SyntaxError:语法无效

1 个答案:

答案 0 :(得分:1)

您可以稍后通过Element.set设置该属性:

root = xml.Element("Tests")
root.set("xsi:noNamespaceSchemaLocation", "anyURI")

或者您可以首先将kwargs打包到Element字典中,然后使用**运算符直接将其解压缩:

root = xml.Element("Tests", **{"xsi:noNamespaceSchemaLocation" : "anyURI"})
相关问题