etree SubElement attribute name class fails

安稳与你 提交于 2019-12-11 20:43:06

问题


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


来源:https://stackoverflow.com/questions/26764634/etree-subelement-attribute-name-class-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!