Это мой XML-документ, я пытаюсь добавить атрибут элемента item в отладчик PyDev в eclipse. Я вижу, что атрибут добавлен, но как только я проверяю новое дерево атрибут не добавляется.Атрибут не добавлен в документ xml с lxml python
Вот 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 из Anaconda:
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