tsspires
tsspires

Reputation: 589

Get Element Tree with Python lxml

I have the following xml record within a larger xml file:

<Employee>
<id>999</id>
<fname>Tim</fname>
<lname>Boskin</lname>
</Employee>

I am attempting to get the fname and lname attributes via lxml and xpath in python. The following statement is not returning anything:

fname = root.xpath('.//Employee[@id="999"]/fname')

Every example I have found and attempted has yielded no results, what would be the proper syntax?

Upvotes: 0

Views: 209

Answers (1)

Cylian
Cylian

Reputation: 11182

@id selects value of the attribute named id.

And this is why it goes wrong. Try this:

fname = root.xpath('//Employee[id/text()="999"]/fname')

Because there is no attribute named id within the Employee element, instead it is a child element of the Employee element. For more details on XPath axes read this.

Upvotes: 1

Related Questions