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

2

6

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!

Lezley answered 2/3, 2015 at 18:18 Comment(6)
@VivekSable Haha thank you :) I'm a tad OCPDLezley
can u check >>> root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"}) is working or not?Aliform
@VivekSable Yes! That definitely worked. I was trying to use those curly brackets before but wasn't sure of the syntax. I'm not sure which implementation is better - this one or Daniel's?Lezley
yes, I also do not no much about this. I read from the lxml.de/tutorial.html , can u look this site also?Aliform
@VivekSable Thanks! I see what it's doing now. I still don't know what the asterisks in Daniel's answer are doing though. Oh well, they both seem to workLezley
Let us continue this discussion in chat.Aliform
A
7

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"})
>>> 
Aliform answered 2/3, 2015 at 19:3 Comment(0)
P
3

Simply use a dictionary

root = ET.Element("databaseConfiguration", **{'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
               'xsi:noNamespaceSchemaLocation':"database.xsd"})
Pishogue answered 2/3, 2015 at 18:40 Comment(2)
Hi Daniel, what is the difference between your answer and what Vivek suggested: >>>root = ET.Element("databaseConfiguration", {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation":"database.xsd"}) e.g. what do the extra asterisks do?Lezley
The double asterisks expand the dictionary as key/value pair arguments for the function call.Compline

© 2022 - 2024 — McMap. All rights reserved.