etree SubElement属性名称类失败

时间:2014-11-05 18:40:14

标签: python xml.etree

我需要强制python(2.7.5)在构建xml文件时使用word class

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

我试过''或""

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

如果我将其更改为其他名称(foo),则会构建xml:

<properties foo="hudson.model.View$PropertyList" />

1 个答案:

答案 0 :(得分:1)

您可以使用attrib={}语法:

head = ET.Element('head')

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

ET.tostring(head)
'<head><properties class="model.View$PropertyList" /></head>'