繁体   English   中英

如何在 Python 中将 XML 属性作为 function 参数传递?

[英]How to pass XML attribute as a function parameter in Python?

我是 Python 的新手。我有一个 XML 文件(“topstocks.xml”),其中包含一些元素和属性,如下所示。 我试图将属性“id”作为 function 参数传递,以便我可以动态获取数据。

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

我的 python 代码是这样的。

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)

应该打印 output。
{'id': 'H02', 'cost': 125000.0, 'state': 'AZ', 'percentage': 0.15, .netIncome': 4500.0}

先感谢您。

尝试这样的事情

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'}

我相信这可以简化为:

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

output 应该是您所期望的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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