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

标签 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。



提前致谢!

最佳答案

以下内容可能对您有用。 从 link 中读取

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

关于python - 如何使用 Python 的 ElementTree 转义属性名称中的冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816728/

相关文章:

python - Matplotlib:共享轴上的不同刻度标签

python - 使用 eval 进行表达式评估的安全性如何?

python - 如何用另一个索引字符串 Python 替换 String 的所有实例

java - AndroidManifest.xml 无法正确编译

php - 转义表名 MySQL

java - 解析 XML,删除 & 之后的所有字符

python - 最小化径向图中的交叉点(networkx、graphviz)

python - 通过python将 'th' 'st' 'rd' 'nd'的日期字符串转换为日期格式

java - Ant/构建 JAR : Build failed, 未找到引用任务.路径

javascript - encodeForHTMLAttribute 与 encodeForJavaScript