1

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?

1 Answer 1

5

"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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.