2014-11-05 18 views
0

我需要強制巨蟒(2.7.5)使用單詞類在構建XML文件etree子元素屬性名稱類失敗

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 

如果我將其更改爲另一個名稱(富),它構建了XML:

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

回答

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

文件 「/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py」,線1052,在_raise_serialization_error 「不能序列%R(類型%type(text,type(text).__ name__) TypeError:can not serialize {'class':'hudson.model.View $ PropertyList'}(輸入字典) – user2363318 2014-11-05 20:14:34

+0

@ user2363318,您是否收到此錯誤在代碼上面運行,還是有另外的元素? – Anzel 2014-11-05 20:16:06

+0

http://pastebin.com/yN3QcP2w這是我做的。 – user2363318 2014-11-05 20:25:11