使用ElementT修改XML文件

2024-09-28 21:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python执行以下操作:

  • 获取“价格”值并更改它
  • 找到“price_-qty”,并根据“price”插入具有新层和不同价格的新行。在
  • 到目前为止,我只能找到价格并更改它,并在大约正确的位置插入行,但我找不到一种方法,如何得到那里的“项目”和“数量”和“价格”属性,到目前为止没有任何工作。。。在

这是我的原始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>

新的xml应该是这样的:

^{pr2}$

目前我的代码:

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")

结果:

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

谢谢你的帮助。在


Tags: nameposimporttreestock价格xmlitem
1条回答
网友
1楼 · 发布于 2024-09-28 21:48:16

不要使用固定索引。你已经有item元素了,为什么不使用它呢?在

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")

相关问题 更多 >