如何在 Python 中将 XML 属性作为函数参数传递?
How to pass XML attribute as a function parameter in Python?
我是 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': 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))
输出
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
输出应该是你所期望的。
我是 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': 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))
输出
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
输出应该是你所期望的。