Scf_suedbaden
Scf_suedbaden

Reputation: 43

Find an attribute based on an elements name in XML on all levels

This is the XML I'm trying to parse:

<State id="1">
    <Initialize>
        <ObjectId value="Obj1" />
        <Start value="Route_1" />
        <Offset value="1.0" unit="m" />
        <Lane value="right1" unit="" />
    </Initialize>
    <Initialize>
            <ObjectId value="Obj2" />
            <Start value="Route_1" />
            <Offset value="1.0" unit="m" />
            <Lane value="right2" unit="" />
    </Initialize>
</State>

I'm using the lxml.etree lib to parse the XML snippet. My goal is to find the value of an attribute by the name of it's element. Example: I want to get the "value" from "ObjectId". If there are multiple "ObjectId" in the entire xml tree, I only want to take the first one. In this case I would like to get "Obj1" as a result.

This is how I'm doing it at the moment:

import lxml.etree as LET
state = LET.XML("state.xml")
variable = "ObjectId"

for attribute in state.iter(variable):
    value = attribute.attrib.get("value")
    print(value)

Is there an alternative to get only the very first "value" of "ObjectId" on all xml levels without using a for-loop?

Thanks for your help!

Upvotes: 0

Views: 448

Answers (1)

balderman
balderman

Reputation: 23815

see below. Just use find

import xml.etree.ElementTree as ET

xml = '''<State id="1">
    <Initialize>
        <ObjectId value="Obj1" />
        <Start value="Route_1" />
        <Offset value="1.0" unit="m" />
        <Lane value="right1" unit="" />
    </Initialize>
    <Initialize>
            <ObjectId value="Obj2" />
            <Start value="Route_1" />
            <Offset value="1.0" unit="m" />
            <Lane value="right2" unit="" />
    </Initialize>
</State>'''

root = ET.fromstring(xml)
print(root.find('.//ObjectId').attrib['value'])

output

Obj1

Upvotes: 2

Related Questions