user2976493
user2976493

Reputation: 67

Escaping python reserved words in xml attributes using the ElementTree library

I'm using the ElementTree library and I have an xml tag that has an attribute with the key called "class". Now this is a reserved word in python obviously. Anyone know how to escape this or if it's even possible?

ownerNode = et.SubElement(rootNode, "Owner")
referenceNode = et.SubElement(ownerNode, class="org.identity", name="john")

^^^ so, how do I escape the class keyword above?

Thanks!

Upvotes: 3

Views: 308

Answers (1)

turbulencetoo
turbulencetoo

Reputation: 3681

Based on the documentation, it looks like you can pass attributes in a dictionary, with the keys as strings:

referenceNode = et.SubElement(ownerNode, "refnode", {"class": "org.identity", "name": "john"})

David Lambert, in a python.org thread discussing this issue, points out that for a function f that only takes keyword arguments, you can do this:

def f(**kwargs):
    print(kwargs)

f(**{'class':'sidebar'})

Upvotes: 3

Related Questions