etree SubElement attribute name class fails
Asked Answered
P

1

0

I need to force python(2.7.5) to use the word class in building a xml file

    properties = ET.SubElement(head, "properties", class="model.View$PropertyList")
                                                       ^
SyntaxError: invalid syntax

I tried '' or ""

    properties = ET.SubElement(head, "properties", "class"="hudson.model.View$PropertyList")
SyntaxError: keyword can't be an expression

If I change it to another name (foo), it builds the xml:

<properties foo="hudson.model.View$PropertyList" />
Pulsifer answered 5/11, 2014 at 18:40 Comment(0)
W
1

You can use attrib={} syntax:

head = ET.Element('head')

properties = ET.SubElement(head, "properties", attrib={'class':"model.View$PropertyList"})

ET.tostring(head)
'<head><properties class="model.View$PropertyList" /></head>'
Welsh answered 5/11, 2014 at 18:52 Comment(4)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1052, in raise_serialization_error "cannot serialize %r (type %s)" % (text, type(text).__name_) TypeError: cannot serialize {'class': 'hudson.model.View$PropertyList'} (type dict)Pulsifer
@user2363318, do you receive this error just by running above code, or do you have another elements?Welsh
I did the wrong import, don't know where I got that from. import xml.etree.cElementTree as ET should be import xml.etree.ElementTree as ETPulsifer
@user2363318, alright I see cElementTree, glad you've solved it :-)Welsh

© 2022 - 2024 — McMap. All rights reserved.