【问题标题】:etree SubElement attribute name class failsetree SubElement 属性名称类失败
【发布时间】:2014-11-05 18:40:14
【问题描述】:

我需要强制python(2.7.5)在构建xml文件时使用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" />

【问题讨论】:

    标签: python xml.etree


    【解决方案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>'
    

    【讨论】:

    • 文件 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py",第 1052 行,在 raise_serialization_error "cannot序列化 %r (type %s)" % (text, type(text).__name_) TypeError: cannot serialize {'class': 'hudson.model.View$PropertyList'} (type dict)
    • @user2363318,您是否仅通过运行上述代码收到此错误,还是您有其他元素?
    • 我做错了导入,不知道我从哪里得到的。 import xml.etree.cElementTree as ET 应该是 import xml.etree.ElementTree as ET
    • @user2363318,好的,我看到了cElementTree,很高兴你解决了它:-)
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多