gpt4 book ai didi

python - 属性未使用 lxml python 添加到 xml 文档

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:19 24 4
gpt4 key购买 nike

这是我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com