在一个非常简单的构建结构中使用etree但是获得了属性错误

时间:2012-12-13 15:18:18

标签: xml elementtree

参考:使用http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/

错误root没有属性extend

        import xml.etree.cElementTree as ET
        import sys
        a = ET.Element('quotationinput version="1.0"')
        b = ET.SubElement(a, 'authorisation')
        c = ET.SubElement(b, 'password')
        c.text = pwd
        d = ET.SubElement(a, 'productdetail')
        e = ET.SubElement(d, 'producttype')
        e.text = ""
        f = ET.SubElement(d, 'accommodationCode')
        f.text = ""
        g = ET.SubElement(d, 'startDate')
        g.text = start_date
        h = ET.SubElement(d, 'duration')
        h.text = duration
        i = ET.SubElement(d, 'unitCode')
        i.text = unit
        j = ET.SubElement(a, 'partydetail')
        k = ET.SubElement(j, 'adultCount')
        k.text = adults
        l = ET.SubElement(j, 'childCount')
        l.text = children
        m = ET.SubElement(j, 'babyCount')
        m.text = baby
        n = ET.SubElement(j, 'petCount')
        n.text = pets
        root = ET.Element('root')
        root.extend([a])
        tree = ET.ElementTree(root)
        tree.write(sys.stdout)

1 个答案:

答案 0 :(得分:0)

扩展方法是2.7中的新方法,因此您可能使用旧版本的python。见http://docs.python.org/2/library/xml.etree.elementtree.html

要解决这个问题,你可以使用像这样的附加方法,它可以很好地工作: -

root.append(a)

以下是未定义变量的虚拟值输出: -

% python.exe s.py
<root><quotationinput version="1.0"><authorisation><password>pwd</password></authorisation><productdetail><producttype /><accommodationCode /><startDate>start_date</startDate><duration>duration</duration><unitCode>unit</unitCode></productdetail><partydetail><adultCount>adults</adultCount><childCount>children</childCount><babyCount>baby</babyCount><petCount>pets</petCount></partydetail></quotationinput version="1.0"></root>