0

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?

1
  • Please ask a new question. Do not add extra stuff to an existing question with an answer that you have accepted. Commented Nov 26, 2021 at 9:21

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot @Sakshi ! Exactly what I wanted. I tried so much.
I have another question. May you can help me. Now, I would like to get the value of val, which is -1 in the same line as lid="diagnosticEcgSpeed" I tried this: x=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val'] But it fails
x=root.find(".//*[@lid='diagnosticEcgSpeed']").attrib['val'] should return the value of 'val' as by passing ".//*[@lid='diagnosticEcgSpeed']" we are geiing the whole dictionary which also contains val as a key in it. {'lid': 'diagnosticEcgSpeed', 'val': '-1', 'pers': '', 'res': '', 'unit': 'mm/s'}
I tried, but I dont get any return: for enter: x=root.find(".//*[@lid='diagnosticEcgSpeed']/preset").attrib['a'] return is: KeyError: 'val' I dont get the attribute of val

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.