1

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

错误根没有属性扩展

        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)
4

1 回答 1

0

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

要解决此问题,您可以使用这样的 append 方法,它也可以很好地工作:-

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>
于 2012-12-13T16:10:23.013 回答