简体   繁体   中英

Modify XML file using ElementTree

I am trying to do the folowing with Python:

  • get "price" value and change it
  • find "price_qty" and insert new line with new tier and different price based on the "price".
  • so far I could only find the price and change it and insert line in about correct place but I can't find a way how to get there "item" and "qty" and "price" attributes, nothing has worked so far...

this is my original 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>

the new xml should look this way:

    <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="10" price="31.20" /> **-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>

my code so far:

import xml.etree.cElementTree as ET
from xml.etree.ElementTree import Element, SubElement

tree = ET.ElementTree(file='pricelist.xml')
root = tree.getroot()
pos=0

# price - raise the main price and insert new tier
for elem in tree.iterfind('pricelist/item/price'):
    price = elem.text
    newprice = (float(price.replace(",", ".")))*1.2    

    newtier = "NEW TIER" 
    SubElement(root[0][pos][5], newtier)
    pos+=1

tree.write('pricelist.xml', "UTF-8")

result:

...
 <price_qty>
        <item price="28.20" qty="150" />
        <item price="26.80" qty="750" />
        <item price="25.60" qty="1500" />
      <NEW TIER /></price_qty>

thank you for any help.

Don't use fixed indexing. You already have the item element, so why don't use it?

tree = ET.ElementTree(file='pricelist.xml')
root = tree.getroot()

for elem in tree.iterfind('pricelist/item'):
    price = elem.findtext('price')
    newprice = float(price.replace(",", ".")) * 1.2

    newtier = ET.Element("item", qty="10", price="%.2f" % newprice)
    elem.find('price_qty').insert(0, newtier)

tree.write('pricelist.xml', "UTF-8")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM