背景
我在 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 和 solution4),其中用户正在解析 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/