通过键属性访问 children

accessing children by key attribute

使用 xml.etree 我需要通过键标识符访问元素。

有例子

<?xml version="1.0" encoding="utf-8" ?>
<Models>
    <Model Id="1" Name="booname" Description="boo" Filter="b">
        <ModelVariables>
            <Variable Id="1" Token="tothh"  />
            <Variable Id="2" Token="avgtt"  />
        </ModelVariables>
        <Terms>
            <Term Id="1" Description="ln1"  Coefficient="0.24160834" />
            <Term Id="2" Description="ln2"  Coefficient="-0.09360441" />
        </Terms>
    </Model>
    <Model Id="2" Name="fooname" Description="foo" Filter="f">
        <Terms>
            <Term Id="1" Description="e1"  Coefficient="0.36310718" />
            <Term Id="2" Description="e2"  Coefficient="-0.24160834" />
        </Terms>
    </Model>
</Models>

如何根据id值访问元素?如果传递参数 2,访问模型所有属性的最直接方法是什么 fooname?

我尝试使用 findtextfindget 方法,但我无法访问所需的元素。

xml.etree.ElementTreesupports a limited XPath language functionality,但这足以通过属性的特定值获取元素:

import xml.etree.ElementTree as ET

data = """<?xml version="1.0" encoding="utf-8" ?>
<Models>
    <Model Id="1" Name="booname" Description="boo" Filter="b">
        <ModelVariables>
            <Variable Id="1" Token="tothh"  />
            <Variable Id="2" Token="avgtt"  />
        </ModelVariables>
        <Terms>
            <Term Id="1" Description="ln1"  Coefficient="0.24160834" />
            <Term Id="2" Description="ln2"  Coefficient="-0.09360441" />
        </Terms>
    </Model>
    <Model Id="2" Name="fooname" Description="foo" Filter="f">
        <Terms>
            <Term Id="1" Description="e1"  Coefficient="0.36310718" />
            <Term Id="2" Description="e2"  Coefficient="-0.24160834" />
        </Terms>
    </Model>
</Models>"""

root = ET.fromstring(data)

id_value = "2"
model = root.findall(".//Model[@Id='%s']" % id_value)[0]
print(model.attrib)

它打印:

{'Id': '2', 'Name': 'fooname', 'Description': 'foo', 'Filter': 'f'}

注意使用 .attrib 访问元素属性。