Friedbert
Friedbert

Reputation: 27

Find element in xml-tree

I want to find in a XML file only the tree with for example code = "7041". Here is a part of the XML file:

<lens>
    <code>7041</code>
    <names>
        <name language="en">
            <long>synchrony SV Curves HDC 1.5 PH Brn</long>
        </name>

</lens>

Here is my code:


   for elem in tree.findall('lenses/lens/code/[@text="7041"]'):
        print (elem.tag, elem.text)

This code does not work, I do not find "7041". What is wrong? How can I select only the part in the file were code="7041"?

Upvotes: 1

Views: 576

Answers (1)

kjhughes
kjhughes

Reputation: 111726

@ is for attributes; for a text node test, use text(),

//lens/code/[@text()="7041"]
             ^

and also remove the spurious / ahead of the predicate:

//lens/code/[text()="7041"]
           ^

to get this XPath expression,

//lens/code[text()="7041"]

will select all of the code element children of lens elements, provided the code element has a text() text node child with a string value of "7041".

You could also test the string value of code,

//lens/code[.="7041"]

If you actually want to select lens elements, elevate the predicate:

//lens[code="7041"]

See also

Thanks to Mads Hansen for correcting a glaring mistake in a previous version of this answer.

Upvotes: 2

Related Questions