我正在研究 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'
我不明白我的錯誤是什么來獲得我的價值 var。
uj5u.com熱心網友回復:
您可以使用以下 xpath:.//setting[@lid='diagnosticEcgSpeed']來檢索元素,然后檢索其屬性。
請參閱以下示例:
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']").attrib["val"]
print(y)
在您的情況下,如果您想直接從檔案中提取此值,您可以使用以下命令:
import xml.etree.ElementTree as ET
tree = ET.parse('./basics.xml')
y=tree.find(".//setting[@lid='diagnosticEcgSpeed']").attrib['val']
print(y)
哪個輸出:
-1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370720.html
上一篇:多行到PHP關聯陣列
