Home > Blockchain >  XML Parsing with Python - find attribute value with Elementtree
XML Parsing with Python - find attribute value with Elementtree

Time:11-30

I am working on XML-Parsing and I want to get the attribute of a sepcific value. I have a XML-file (see bellow) and I want to get the value of val in the second line after lid="diagnosticEcgSpeed" which is -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>

I tried so far this code:

import xml.etree.ElementTree as ET
tree = ET.parse('basics.xml')
root = tree.getroot()

y=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val']
print(y)

And the return is

Traceback (most recent call last):
  File "parsing_example.py", line 5, in <module>
  y=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val']
KeyError: 'val'

I don't understand what my error is to get my value var.

CodePudding user response:

You can use the following xpath: .//setting[@lid='diagnosticEcgSpeed'] to retrieve the element and then retrieve its attribute.

See the example below:

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)

In your case if you want to extract this value directly from a file you can use the following:

import xml.etree.ElementTree as ET
tree = ET.parse('./basics.xml')
y=tree.find(".//setting[@lid='diagnosticEcgSpeed']").attrib['val']
print(y)

Which output:

-1
  • Related