如何使用 Python 的 ElementTree 转义属性名称中的冒号?

How do I escape colons in an attribute name with Python's ElementTree?

背景

我在 Python 2.6 版中使用 ElementTree 创建一个 XML 文件(使用从数据库检索的数据)。

代码

以下代码行是问题区域,因为我的属性名称中有冒号,所以我不断收到语法错误。

# Please ignore any errors the "^" characters would cause if they were
# actually part of my code - just using them as placeholders.

root = ET.Element("databaseConfiguration", xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",
                                                ^
                  xsi:noNamespaceSchemaLocation="database.xsd")
                     ^

问题

为了使 root 等同于以下内容,转义这些属性名称中的冒号的最有效方法是什么:

<databaseConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="database.xsd"/>

备注

我查看了 Stack Overflow 上的一些解决方案(例如 solution1, solution2, solution3 and solution4),其中用户正在解析 XML 文件,但我似乎无法将这些修复解释为适用于写入 XML.



提前致谢!

简单地使用字典

root = ET.Element("databaseConfiguration", **{'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
               'xsi:noNamespaceSchemaLocation':"database.xsd"})

以下内容可能对您有用。 阅读 link

>>> root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"})
>>>