这是我的 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>
最佳答案
此代码应该按照您的要求工作:
from io import StringIO
from lxml import etree
fileName = '...'
context = etree.iterparse(fileName, tag='item')
for _, element in context:
element.attrib['DocumentCode'] = 'the value of the attr'
with open(fileName, 'wb') as f:
f.write(etree.tostring(context.root, pretty_print=True))
关于python - 属性未使用 lxml python 添加到 xml 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40948164/