xyz-123
xyz-123

Reputation: 2237

XPath: match multiple elements in one expression

I'm trying to do this (using lxml):

//*[@id="32808345" or @id="33771423" or @id="15929470" or @id="33771117" or @id="15929266"]

in order to get all elements, no matter what tag, with the specified id's. I'm getting the following traceback:

invalid attribute predicate

this is how I'm generating the str (if that is relevant to the problem):

refs = ' or '.join('@id="%s"' % ref for ref in refs[0:5])
elements = etree.iterfind('//*[%s]' % refs)

EDIT, with the below solution I'm getting this error:

File "lxml.etree.pyx", line 1201, in lxml.etree._Element.iterchildren (src/lxml/lxml.etree.c:36294)
  File "lxml.etree.pyx", line 2163, in lxml.etree.ElementChildIterator.__init__ (src/lxml/lxml.etree.c:45331)
  File "lxml.etree.pyx", line 2118, in lxml.etree._ElementTagMatcher._initTagMatch (src/lxml/lxml.etree.c:44913)
  File "apihelpers.pxi", line 1413, in lxml.etree._getNsTag (src/lxml/lxml.etree.c:21412)
ValueError: Empty tag name

Upvotes: 2

Views: 4153

Answers (2)

Paddy O'Loughlin
Paddy O'Loughlin

Reputation: 1712

Try using the xpath method instead of iterfind.

I think the iterfind method doesn't accept all XPath expressions.

Upvotes: 2

kander
kander

Reputation: 4306

The normal way to do this is using the single pipe operator, I believe?

//*[@id="20"] | //*[@id="30"] | ... etc.

Do you have a snippet of the XML you're trying to do this on?

Upvotes: 6

Related Questions