etree SubElement attribute name class fails

2019-09-08 04:10发布

问题:

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" />

回答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>'