我有以下问题:我有一个xml文件,我通过xml.etree.ElementTree解析它具有以下结构
<e3r>
<moreData>false</moreData>
<data>
<CashDividend Isin="IE00BYM8JD58" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor=""/>
<CashDividend Isin="IE00BZ163G84" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" Amount_Status=""/>
<CashDividend Isin="IE00BZ163H91" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor=""/>
<CashDividend Isin="IE00BZ163M45 " AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" />
</data>
</e3r>
我通过API获取标签AdjustmentFactor的一些数据(我使用Isin获取数据),我想要实现的是将我用API获得的数据添加到AdjustmentFactor。 (与伊辛有关)。我无论如何都无法解决这个问题。
这就是我获得每个ISIN的方式:
isins = []
for child in tree.getroot().getchildren()[1].getchildren():
isins.append(child.attrib['Isin'])
for isin in isins:
print isin
但我不知道如何使用列表isins中存储的数据向AdjustmentFactor添加数据。
有人可以协助吗?
答案 0 :(得分:1)
问题中没有明确说明,但如果我理解正确,您希望更新AdjustmentFactor
属性等于某个值的元素的Isin
属性值。您可以使用类似.//element_name[@attribute_name='attribute_value']
的XPath表达式按属性值查找元素。
工作演示示例:
from xml.etree import ElementTree as et
raw = '''<e3r>
<moreData>false</moreData>
<data>
<CashDividend Isin="IE00BYM8JD58" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor=""/>
<CashDividend Isin="IE00BZ163G84" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" Amount_Status=""/>
<CashDividend Isin="IE00BZ163H91" AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor=""/>
<CashDividend Isin="IE00BZ163M45 " AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" />
</data>
</e3r>'''
root = et.fromstring(raw)
isin = "IE00BYM8JD58"
adjustment_factor = "FOO"
element = root.find(".//CashDividend[@Isin='%s']" % isin)
element.set("AdjustmentFactor", adjustment_factor)
print et.tostring(root)
<强> eval.in demo
强>
输出
<e3r>
<moreData>false</moreData>
<data>
<CashDividend AdjustmentFactor="FOO" Adjustment_Date="" Adjustment_Factor="" Isin="IE00BYM8JD58" />
<CashDividend AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" Amount_Status="" Isin="IE00BZ163G84" />
<CashDividend AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" Isin="IE00BZ163H91" />
<CashDividend AdjustmentFactor="" Adjustment_Date="" Adjustment_Factor="" Isin="IE00BZ163M45 " />
</data>
</e3r>