Python ElementTree如何将变量的值发送到xml输出

时间:2015-04-16 23:31:21

标签: python xml elementtree

我想用lastrun日期属性中的当前日期更新xml文件。 以下代码会生成+ str(mprocessdate) +,我希望它说2015-04-16

我的代码出了什么问题?为什么我得到那个字符串而不是实际日期?

company1.xml

<corp>
<lastrun date="20150123" />
<company id="18888802223">
    <name>South Plantation</name>
    <P_DNIS>99603</P_DNIS>
    <Tracking_Phone>+18888802223</Tracking_Phone>
    <Account>South Plantation</Account>
    <AppendValue> Coupon</AppendValue>
    <InsertCoupon>Y</InsertCoupon>
 </company>
</corp>

脚本

import datetime
from xml.etree import ElementTree as ET

mprocessdate = datetime.date.today()
print (mprocessdate)
tree = ET.parse("company1.xml")
mlastrun = tree.find('lastrun')
mlastrun.set('date', '+ str(mprocessdate) + ')
tree.write('company.xml')

1 个答案:

答案 0 :(得分:1)

不要使用+,只需输入变量名称。

import datetime
from xml.etree import ElementTree as ET

mprocessdate = datetime.date.today()
print (mprocessdate)

tree = ET.parse("company.xml")

mlastrun = tree.find('lastrun')

mlastrun.set('date', str(mprocessdate))

tree.write('company.xml')
相关问题