Ted Ted - 2 months ago 8
Python Question

Search XML for Variable Attribute Using Python & ElementTree

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

<file id="file-10">
<clip>1</clip>
<timecode>1:00:00:00</timecode>
</file>
<file id="file-11">
<clip>2</clip>
<timecode>2:00:00:00</timecode>
</file>


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
ElementTree
? Should I be using something else?

Answer

"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:

root.find('file[@id="{value}"]'.format(value=fileid))