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

时间:2015-03-02 18:18:26

标签: python xml escaping python-2.6 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上的一些解决方案(例如solution1solution2solution3solution4)用户正在解析XML文件,但我似乎无法将这些修复解释为可以用于写入XML的修复。



提前致谢!

2 个答案:

答案 0 :(得分:4)

可能会对您有所帮助。 请阅读link

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

答案 1 :(得分:2)

只需使用字典

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