2016-12-03 5 views
1

これは私のXML文書です。アイテム要素に属性を追加しようとしています。EclipseのPyDevデバッガで属性が追加されていますが、属性は追加されません。ここでXML文書に属性が追加されていない

は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を使用して私のコードです:

   <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()'という行を削除します。 * "要素をリセットします。この関数はすべてのサブ要素を削除し、すべての属性をクリアし、テキストとテールのプロパティをNoneに設定します。" * [[documentation](http://lxml.de/api/lxml.etree._Element-class。 html)] – har07

答えて

1

このコード必要があります。

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) 

私が目指すこれが何をされますあなたが望むように働く:

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) 

これは、スタンドアロンのlibで可能です。

関連する問題