Ted Ted - 1 year ago 82
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download