Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 672
Kimbluey Avatar asked Mar 02 '15 18:03

Kimbluey


2 Answers

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"})
>>> 
like image 103
Vivek Sable Avatar answered Nov 03 '22 05:11

Vivek Sable


Simply use a dictionary

root = ET.Element("databaseConfiguration", **{'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
               'xsi:noNamespaceSchemaLocation':"database.xsd"})
like image 36
Daniel Avatar answered Nov 03 '22 03:11

Daniel