[英]How to pass XML attribute as a function parameter in Python?
I am new to Python. I have a XML file("topstocks.xml") with some elements and attributes which looks like as below.我是 Python 的新手。我有一个 XML 文件(“topstocks.xml”),其中包含一些元素和属性,如下所示。 I was trying to pass an attribute "id" as a function parameter, so that I can dynamically fetch the data.我试图将属性“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>
My python code goes like this.我的 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)
It's output should print.应该打印 output。
{'id': 'H02', 'cost': 125000.0,'state': 'AZ', 'percentage': 0.15, .netIncome': 4500.0} {'id': 'H02', 'cost': 125000.0, 'state': 'AZ', 'percentage': 0.15, .netIncome': 4500.0}
Thank you in advance.先感谢您。
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 output
None
{'id': 'H03', 'cost': '119000', 'state': 'NH', 'percentage': '0.13', 'data': '3248.7'}
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. output 应该是您所期望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.