Home > Mobile >  How to pass XML attribute as a function parameter in Python?
How to pass XML attribute as a function parameter in Python?

Time:03-28

I am new to Python. I have a XML file("topstocks.xml") with some elements and attributes which looks like as below. I was trying to pass an attribute "id" as a function parameter, so that I can dynamically fetch the data.

<properties>
    <property id="H01" cost="106000" state="NM" percentage="0.12">2925.6</property>
    <property id="H02" cost="125000" state="AZ" percentage="0.15">4500</property>
    <property id="H03" cost="119000" state="NH" percentage="0.13">3248.7</property>
</properties>

My python code goes like this.

import xml.etree.cElementTree as ET
tree = ET.parse("topstocks.xml")
root = tree.getroot()

def find_all(id ='H02'):   # I am trying to pass attribute "id"
    stocks = []
    for child in root.iter("property"):
        data = child.attrib.copy()
        data["cost"] = float(data["cost"])
        data["percentage"] = float(data["percentage"])
        data["netIncome"] = float(child.text)
        stocks.append(data)
    return stocks

def FindAll(id ='H02'):
    settings = find_all(id)  
    return settings

if __name__=="__main__":
    idSelection = "H02"

result= FindAll(id=idSelection)
print(result)

It's output should print.
{'id': 'H02', 'cost': 125000.0,'state': 'AZ', 'percentage': 0.15, 'netIncome': 4500.0}

Thank you in advance.

CodePudding user response:

Try something like this

import xml.etree.ElementTree as ET

xml = """
<properties>
    <property id="H01" cost="106000" state="NM" percentage="0.12">2925.6</property>
    <property id="H02" cost="125000" state="AZ" percentage="0.15">4500</property>
    <property id="H03" cost="119000" state="NH" percentage="0.13">3248.7</property>
</properties>
"""

def find_by_id(_id,xml_root):
  prop = xml_root.find(f'.//property[@id="{_id}"]')
  if prop is not None:
    temp = prop.attrib
    temp['data'] = prop.text
    return temp
  else:
    return None
root = ET.fromstring(xml)
print(find_by_id('ttt',root))
print(find_by_id('H03',root))

output

None
{'id': 'H03', 'cost': '119000', 'state': 'NH', 'percentage': '0.13', 'data': '3248.7'}

CodePudding user response:

I believe this could be simplified to:

root = ET.fromstring(invest)
stocks = {}
target= root.find('.//properties/property[@id="H02"]')
if target is not None:
    stocks.update(target.items())
    stocks['netIncome']=target.text

stocks

The output should be what you expect.

  • Related