使用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
的所有属性吗?
我尝试使用findtext
,find
和get
方法以及参数的变体但我无法访问所需的元素。
答案 0 :(得分:0)
xml.etree.ElementTree
supports 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
访问元素属性。