AttributeError:'NoneType'对象没有属性'text'

时间:2015-06-15 17:34:09

标签: python lxml

这就是我所拥有的,当你用他的参数调用函数时,这段代码将生成一个Xml文件。

from lxml import etree

root = etree.Element("UpdateInventoryRequest")
doc = etree.ElementTree(root)

start_date_sard = root.append(etree.Element("StartDate"))
room_id_sard = root.append(etree.Element("RoomId"))
root.append(etree.Element("Data"))
data_root = root[2]
availability_in_data = data_root.append(etree.Element("Availability"))
price_in_data = data_root.append(etree.Element("Price"))


def buildXmlUpdate(dfrom, roomId, ldays):   

    start_date_sard.text = dfrom
    roomId = str(roomId)  
    room_id_sard.text = roomId


    for n in ldays:
        print (dfrom, roomId, n)
        #availability_in_data.text = get.ldays['avail']
        #price_in_data.txt = get.ldays['price']
        ldays[-1]['avail'] = str(ldays[-1]['avail'])
        ldays[-1]['price'] =str(ldays[-1]['price'])
        availability_in_data.text = ldays[-1]['avail']
        price_in_data.text = ldays[-1]['price']


#here execute the function 

buildXmlUpdate('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
doc.write('testoutput.xml', pretty_print=True)

这就是我收到的:

AttributeError: 'NoneType' object has no attribute 'text'

会发生什么?

2 个答案:

答案 0 :(得分:0)

根据lxml tutorial,您应该使用您创建的对象访问节点,而不是append函数的返回值。

示例:

root = etree.Element("UpdateInventoryRequest")
root.text = "this is a text"

答案 1 :(得分:0)

解决:

from lxml import etree
# Create Xml
root = etree.Element("UpdateInventoryRequest")
doc = etree.ElementTree(root)

root.append(etree.Element("StartDate"))
root.append(etree.Element("RoomId"))
root.append(etree.Element("Data"))
data_root = root[2]
data_root.append(etree.Element("Availability"))
data_root.append(etree.Element("Price"))
# Xml in code

def buildXmlUpdate(dfrom, roomId, ldays):   
    start_date_sard = dfrom
    roomId = str(roomId)  
    room_id_sard = roomId

    for n in ldays:
        print (dfrom, roomId, n)
        ldays[-1]['avail'] = str(ldays[-1]['avail'])
        ldays[-1]['price'] =str(ldays[-1]['price'])
        availability_in_data = ldays[-1]['avail']
        price_in_data = ldays[-1]['price']

    root[0].text = start_date_sard
    root[1].text = room_id_sard
    data_root[0].text = availability_in_data
    data_root[1].text = price_in_data

#here execute the function 

buildXmlUpdate('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
doc.write('testoutput.xml', pretty_print=True)