Monday, 2 March 2015

How to avoid inserting xml element using fixed indexing with python element tree



I have xml file in which I am inserting line with another price tier. The xml is very large (about 20.000 lines) but I can not find a way how to insert the element using elem.find, only what works is fixed indexing but this brings many problems because the xml is not same everywhere so sometimes I am inserting element in wrong place.


this is part of the xml:



<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<body start="20.04.2014 10:02:60">
<pricelist>
<item>
<name>LEO - red pen</name>
<price>31,4</price>
<price_snc>0</price_snc>
<price_ao>0</price_ao>
<price_qty>
<item qty="150" price="28.20" />
<item qty="750" price="26.80" />
<item qty="1500" price="25.60" />
</price_qty>
<stock>50</stock>
</item>
</pricelist>


this is what I need to get after runnning the code (and I really get it but not everywhere because of the fixed indexing problem):



<pricelist>
<item>
<name>LEO - red pen</name>
<price>37,68</price>
<price_snc>0</price_snc>
<price_ao>0</price_ao>
<price_qty>
<item qty="10" price="31.40" /> - *** this is the new line
<item qty="150" price="28.20" />
<item qty="750" price="26.80" />
<item qty="1500" price="25.60" />
</price_qty>
<stock>50</stock>
</item>
</pricelist>


and this is relevant part of the code. I have to first look for the "price", and then calculate the new price and insert it in "price_qty" part. I have tried with elem.find but it always finds the first one so I keep changing first product and never go ahead.



import xml.etree.cElementTree as ET
tree = ET.ElementTree(file='pricelist.xml')
root = tree.getroot()
pos=0
for elem in tree.iterfind('pricelist/item/price'):
price = elem.text
tierprice = (float(price.replace(",", ".")))
elem.text = str(tierprice)
if tierprice <= 500:
newprice = (float(price.replace(",", ".")))*1.2
elem.text = str(newprice)
newtier = ET.Element("item", qty="3", price="%.2f" % tierprice)
root[0][pos][5].insert(0,newtier)
pos+=1
else:
pos+=1
tree.write('pricelist.xml', "UTF-8")

No comments:

Post a Comment