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

Kim*_*uey 5 python xml escaping elementtree python-2.6

背景

我在 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")
                     ^
Run Code Online (Sandbox Code Playgroud)

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

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

笔记

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



提前致谢!

Viv*_*ble 6

可能以下对你有用。从链接阅读

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