How do I escape colons in an attribute name with Python's ElementTree?

£可爱£侵袭症+ 提交于 2019-12-23 15:26:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!