XPath expression to find elements whose tag name contains 'Name'

user2082317 picture user2082317 · Feb 18, 2013 · Viewed 40.8k times · Source

I am a newcomer to XPath.

I am looking for a way to get all elements whose tag name contains a particular string.

For example, if I have XML like below, I want to get all the elements whose tag name contains the word 'Name'. i.e., I want to fetch the following elements: <SquareName>, <RectangleName>, and <ParallelogramName>.

I tried some combinations of name(), contains() etc., but it did not work. Please suggest.

<Objects>
 <Four-Sided>
   <Square>
      <SquareName>ABCD</SquareName>
      <Length>4</Length>
      <Height>4</Height>
      <Colour>Blue</Colour>
   </Square>
   <Rectangle>
      <RectangleName>EFGH</RectangleName>
      <Length>10</Length>
      <Height>6</Height>
      <Colour>Brown</Colour>
   </Rectangle>
   <Parallelogram>
      <ParallelogramName>WXYZ</ParallelogramName>
      <Length>12</Length>
      <Height>4</Height>
      <Colour>Black</Colour>
   </Parallelogram>
</Four-Sided>
</Objects>

Answer

Jens Erat picture Jens Erat · Feb 18, 2013

For an XPath solution:

//*[contains(local-name(), 'Name')]