如何使用Python的ElementTree在属性名称中转义冒号? [英] How do I escape colons in an attribute name with Python's ElementTree?
问题描述
我正在Python 2.6版中使用ElementTree创建XML文件(使用从数据库中检索到的数据)。
I am using ElementTree in Python version 2.6 to create an XML file (using data retrieved from a database).
下面的代码行是问题区域,因为由于属性名中的冒号,我不断出现语法错误。
The following line of code is the problem area, as I keep getting a syntax error because of the colons within my attribute names.
# 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
等效于以下内容,最有效的方法是在这些属性名称中转义冒号:
Question
What is the most efficient way to escape the colons in these attribute names in order to have root
equivalent to the following:
< databaseConfiguration xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation = database.xsd />
我在堆栈溢出(例如 solution1 , solution2 ,solution3 和解决方案4 ),但我似乎无法将这些修补程序解释为可用于写入XML的修补程序。
I've looked at a few solutions on Stack Overflow (e.g. solution1, solution2, solution3 and solution4) where users were parsing an XML file, but I cannot seem to interpret these fixes as ones that would work for writing to an XML.
谢谢!
推荐答案
可能对您有用。
从链接
>>> root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"})
>>>
这篇关于如何使用Python的ElementTree在属性名称中转义冒号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!