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

2024-04-18 21:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: thenamebranchsizedatetimeindex属性is
2条回答
import xml.etree.ElementTree as et
with open(filename, 'r+b') as f:
    tree = et.parse(f):
    [tr.attrib.update({"aaaa":"bbbb"}) for tr in tree.iter() if tr.tag== "item"]
    tr.write(output)

这里有可能做到这一点与标准库。你知道吗

此代码应按您的需要工作:

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))

相关问题 更多 >