2012-12-13 32 views
1

參考:使用http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/在一個非常簡單的構建結構etree但得到一個屬性錯誤

錯誤根本沒有屬性擴展

 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) 

回答

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> 
相關問題