我在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的修复。
提前致谢!
答案 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"})