如何使用Python'对属性名中的冒号进行转义;什么是元素树? 背景
我正在使用Python 2.6版中的ElementTree创建一个XML文件(使用从数据库检索的数据) 代码 下面这行代码就是问题所在,因为我的属性名中有冒号,所以一直出现语法错误如何使用Python'对属性名中的冒号进行转义;什么是元素树? 背景,python,xml,escaping,python-2.6,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("databa
# 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
等效于以下内容,对这些属性名称中的冒号进行转义的最有效方法是什么:
笔记
我已经研究了一些关于堆栈溢出(例如和)的解决方案,其中用户正在解析XML文件,但我似乎无法将这些修复解释为可用于写入XML的修复
提前谢谢 只需使用字典即可
root = ET.Element("databaseConfiguration", **{'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
'xsi:noNamespaceSchemaLocation':"database.xsd"})
可能是以下将为您工作。 从报纸上读到
@VivekSable哈哈谢谢:)我是一个小小的OCPDcan u检查
>>root=ET.Element(“数据库配置”,{“xmlns:xsi”:http://www.w3.org/2001/XMLSchema-instance,“xsi:noNamespaceSchemaLocation”:“database.xsd”})
是否工作?@VivekSable是!这确实奏效了。我以前尝试过使用这些花括号,但不确定语法。我不确定哪种实现更好——这一个还是Daniel的?是的,我对此也不太了解。我从网上看到,你也可以看看这个网站吗?@VivekSable谢谢!我知道它现在在做什么。我仍然不知道丹尼尔答案中的星号在做什么。哦,好吧,它们似乎都有效嗨,丹尼尔,你的答案和Vivek建议的有什么区别:>>root=ET.Element(“数据库配置”,{“xmlns:xsi”:http://www.w3.org/2001/XMLSchema-instance“,“xsi:noNamespaceSchemaLocation”:“database.xsd”})
例如,额外的星号有什么作用?感谢您的帮助!
>>> root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"})
>>>