這是我的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>
你能給出一個需要輸出的例子嗎? –
我編輯了答案,添加了我正在尋找的示例輸出,請檢查項目元素,新屬性是我嘗試添加的最後一個。 –
刪除該行:'element.clear()'。 *「重置元素,該函數刪除所有子元素,清除所有屬性,並將文本和尾部屬性設置爲無。」* [[documentation](http://lxml.de/api/lxml.etree._Element-class。 html)] – har07