2016-12-03 43 views
1

這是我的XML文檔,我試圖將屬性添加到項目元素,在Eclipse的PyDev調試我看到屬性添加,但一旦我檢查新樹該屬性不被添加。屬性不會被添加到XML文檔與LXML蟒蛇

這裏是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> 

下面是使用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> 
+0

你能給出一個需要輸出的例子嗎? –

+0

我編輯了答案,添加了我正在尋找的示例輸出,請檢查項目元素,新屬性是我嘗試添加的最後一個。 –

+3

刪除該行:'element.clear()'。 *「重置元素,該函數刪除所有子元素,清除所有屬性,並將文本和尾部屬性設置爲無。」* [[documentation](http://lxml.de/api/lxml.etree._Element-class。 html)] – har07

回答

1

此代碼應按你想要的方式工作:

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

小提醒:https://stackoverflow.com/help/someone-answers,如果答案對你有好處:) –

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

以下是使用standart lib做到這一點的可能性。