[英]XML Parsing with Python - find attribute value with Elementtree
我正在研究 XML 解析,我想获得一个特定值的属性。 我有一个 XML 文件(见下文),我想在 lid="diagnosticEcgSpeed" 之后的第二行中获取 val 的值,即 -1。
<global>
<setting lid="diagnosticEcgSpeed" val="-1" pers="" res="" unit="mm/s">
<txt id="001041" description="" type="">Geschwindigkeit</txt>
<value lid="1" val="-1" text="50"/>
<value lid="2" val="-2" text="25"/>
<value lid="4" val="-4" text="12,5"/>
<!-- todo: only one value is needed -> use adult value -->
<preset i="-1" c="-1" a="-1" />
</setting>
<setting lid="diagnosticEcgScale" val="10" unit="mm/mV" pers="" res="">
<txt id="001040" description="" type="">Amplitudenskalierung</txt>
<value lid="2" val="2" />
<value lid="5" val="5" />
<value lid="10" val="10" />
<value lid="20" val="20" />
<!-- todo: only one value is needed -> use adult value -->
<preset i="10" c="10" a="10" />
</setting>
</global>
到目前为止,我尝试了这段代码:
import xml.etree.ElementTree as ET
tree = ET.parse('basics.xml')
root = tree.getroot()
y=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val']
print(y)
回报是
Traceback (most recent call last):
File "parsing_example.py", line 5, in <module>
y=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val']
KeyError: 'val'
我不明白我的错误是什么以获得我的价值变量。
您可以使用以下 xpath:.//setting[@lid='diagnosticEcgSpeed']/ .//setting[@lid='diagnosticEcgSpeed']/value
请参见下面的示例:
data = """
<global>
<setting lid="diagnosticEcgSpeed" val="-1" pers="" res="" unit="mm/s">
<txt id="001041" description="" type="">Geschwindigkeit</txt>
<value lid="1" val="-1" text="50"/>
<value lid="2" val="-2" text="25"/>
<value lid="4" val="-4" text="12,5"/>
<!-- todo: only one value is needed -> use adult value -->
<preset i="-1" c="-1" a="-1" />
</setting>
</global>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(data)
y=tree.find(".//setting[@lid='diagnosticEcgSpeed']/value").attrib["val"]
print(y)
其中output:
-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.