簡體   English   中英

使用Python在XML文件中查找和更改屬性

[英]Using Python to find and change attribute in an XML file

我一直在嘗試找出如何使用百分比變化以及在-90 < percentChange < 100范圍內更改“希臘纈草”植物的價格。

我可以找到並手動更改名稱和數字,只是不知道如何使用百分比更改,並且正在使用Py Charm社區版。 代碼中的outputt.xml文件是我將更改寫入第二個文件。

我的XML代碼段是:

<PLANT>    
    <COMMON>Greek Valerian</COMMON>    
    <BOTANICAL>Polemonium caeruleum</BOTANICAL>    
    <ZONE>Annual</ZONE>
    <LIGHT>Shade</LIGHT>    
    <PRICE>4.36</PRICE>    
    <AVAILABILITY>071499</AVAILABILITY>    
</PLANT>
<PLANT>    
    <COMMON>California Poppy</COMMON>    
    <BOTANICAL>Eschscholzia californica</BOTANICAL>
    <ZONE>Annual</ZONE>    
    <LIGHT>Sun</LIGHT>   
    <PRICE>7.89</PRICE>    
    <AVAILABILITY>032799</AVAILABILITY>
</PLANT>

到目前為止,我得到的Python3代碼是:

import xml.etree.ElementTree as ET

with open('plant_catalog.xml', encoding='latin-1') as f:
  tree = ET.parse(f)
  root = tree.getroot()

  for elem in root.getiterator():
    try:
      elem.text = elem.text.replace('4.36', '5')
    except AttributeError:
      pass    
tree.write('outputt.xml', encoding='latin-1')

誰能幫我解決這個問題?

只需將價格更改為

current_price*(1+percentChange/100)

首先找到您感興趣的植物:

for plant in root.iter('COMMON'):
    if plant.text!='Greek Valerian':
        continue
    else:
        price = None
        for i in range(4):
            price = plant.getnext()
        price.text = str(float(price.text)*(1+percentChange/100))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM