XPath expression to find elements whose tag name contains 'Name'
Asked Answered
B

2

29

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>
Barocchio answered 18/2, 2013 at 7:41 Comment(0)
C
41

For an XPath solution:

//*[contains(local-name(), 'Name')]
Caia answered 18/2, 2013 at 9:18 Comment(2)
After looking at the result, I find that among the Elements that is returns, I need to avoid one element with tag name as 'PeriodName'. I can programatically do that but was wondering if XPath has a solution for that also ?Barocchio
You could either use regular expressions or if it's only for this one, another predicate (or combine them using or): //*[contains(local-name(), 'Name')][local-name() != 'PeriodName']Caia
P
1

Since there is no Namespace prefix, you can also use

//*[contains(name(), 'Name')]
Penetrant answered 19/10, 2016 at 7:11 Comment(1)
Close to the solution.Northampton

© 2022 - 2024 — McMap. All rights reserved.