Ted Ted - 8 months ago 34
Python Question

Search XML for Variable Attribute Using Python & ElementTree

I have an XML that looks like this (simplified):

<file id="file-10">
<file id="file-11">

I'm trying to use ElementTree to search for a file element with a particular id attribute.
This works:

correctfile = root.find('file[@id="file-10"]')

This does not:

fileid = 'file-10'
correctfile = root.find('file[@id=fileid]')

I get:

SyntaxError: invalid predicate

Is that a limitation of
? Should I be using something else?


"SyntaxError: invalid predicate"

file[@id=fileid] is an invalid XPath expression because you miss the quotes around the attribute value. If you put the quotes around the fileid: file[@id="fileid"] the expression would become valid, but it is not gonna find anything since it would search for the file elements with id equals to "fileid" string.

Use string formatting to insert the fileid value into the XPath expression: