问题
Background
I am using ElementTree in Python version 2.6 to create an XML file (using data retrieved from a database).
Code
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")
^
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"/>
Notes
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.
Thanks in advance!
回答1:
may be following will work for you. Read from the link
>>> root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"})
>>>
回答2:
Simply use a dictionary
root = ET.Element("databaseConfiguration", **{'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
'xsi:noNamespaceSchemaLocation':"database.xsd"})
来源:https://stackoverflow.com/questions/28816728/how-do-i-escape-colons-in-an-attribute-name-with-pythons-elementtree