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

标签 python xml lxml attr

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

相关文章:

python - 将列表中的每个项目重复另一个列表中指定的次数

java - Android 特定用户界面

python - 'charmap' 编解码器无法解码位置 33222 : character maps to <undefined> 中的字节 0x8d

python - 使用 lxml.etree 在 Python 中解析 XML

python - Pandas 用重复的索引值填充组内缺失的日期和值

python - 为什么 str(super(B, b)) 不等于 super(B, b).__str__()?

android - 我想将 Scrollview 添加到 Button?

python - xpath lxml无法获取html的ul标签内的所有元素

python - 如何在丢失之前运行两次keras模型?

c# - Web API - 动态到 XML 序列化