这是我的XML文档,我正在尝试向item元素添加一个属性,在eclipse的PyDev调试器中,我看到属性被添加了,但是一旦我检查了新的树,属性就没有添加。你知道吗
以下是XML:
<root>
<login branch="99">
<command action="create">
<goods_transfer type="9" book="true" nummer="692" branch_from="99" branch_to="90" CheckQty="0">
<item article="100500213" main_price="49.950" EAN="5018746059881" amount="1.000" DateTime="20161202112913">
<size amount="1.000" index="59" EAN="5018746059881" Name="S 37/38" DateTime="20161202112913">
</size>
</item>
<item article="100500213" main_price="49.950" EAN="5018746059898" amount="2.000" DateTime="20161202112914">
<size amount="2.000" index="60" EAN="5018746059898" Name="M 39/40" DateTime="20161202112914">
</size>
</item>
</goods_transfer>
</command>
</login>
</root>
下面是我使用Anaconda的Python 3.4编写的代码:
with open(fileName, 'r+b') as f:
tree = etree.parse(f)
for _,element in etree.iterparse(f, tag='item'):
#After this line is executed I see the attribute is added
element.attrib['DocumentCode'] = 'the value of the attr'
element.clear()
#When I check the new file the attribute is not added
tree.write(fileName)
我的目标是:
<item article="100500213" main_price="49.950" EAN="5018746059881" amount="1.000" DateTime="20161202112913" DocumentCode='the value of the attr'>
<size amount="1.000" index="59" EAN="5018746059881" Name="S 37/38" DateTime="20161202112913">
</size>
</item>
这里有可能做到这一点与标准库。你知道吗
此代码应按您的需要工作:
相关问题 更多 >
编程相关推荐