我是Python的新手。我有一个XML文件("topstocks.XML"(,其中包含一些元素和属性,如下所示。我试图传递一个属性";id";作为函数参数,这样我就可以动态地获取数据。
<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)
它的输出应该打印出来
{‘id’:‘H02’,‘cost’:12500.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))
输出
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
输出应该是您所期望的。