psad
psad

Reputation: 23

XML Parsing with Python - find attribute value in XML file

I am working new in Parsing and have an issue which I dont know how to solve.

I have a XML-file (see bellow) and I just want to get the value of the a in preset, 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>

I tried so far this code:

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

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

and I get:

{'i': '-1', 'c': '-1', 'a': '-1'}

What do I need to change in my codes so that I get just the value of a and not all attributes in preset?

Upvotes: 0

Views: 815

Answers (1)

Sakshi Sharma
Sakshi Sharma

Reputation: 133

Since the returned value is a dictionary itself, you can try

import xml.etree.ElementTree as ET
tree = ET.parse(r"C:\Users\πŸ…‚πŸ„°πŸ„ΊπŸ…‚πŸ„·πŸ„Έ\Downloads\new downloads\temp\abc.xml")
root = tree.getroot()

x=root.find(".//*[@lid='diagnosticEcgSpeed']/preset").attrib['a']
print(x)

Upvotes: 2

Related Questions