15

I can search for a String contained in an specific attribute if I use the following XPath /xs:schema/node()/descendant::node()[starts-with(@my-specific-attribute-name-here, 'my-search-string')]

However, I'd like to search for ANY attribute containing* a String

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
emdog4
  • 1,975
  • 3
  • 20
  • 25
  • You need to be clear what you mean by "containing". Do you mean "equal to", or "having a substring equal to"? Or, as your example suggests, "starting with"? – Michael Kay Sep 13 '11 at 16:54

3 Answers3

22

Sample XML:

<root>
  <element1 a="hello" b="world"/>
  <element2 c="world" d="hello"/>
  <element3 e="world" f="world"/>
</root>

Suppose, we need to select elements which have any attribute containing h. In this sample: element1, element2. We can use this XPath:

//*[@*[starts-with(., 'h')]]

In your sample:

/xs:schema/node()/descendant::node()
    [@*[starts-with(@my-specific-attribute-name-here, 'my-search-string')]]
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • Is `//*[@*[starts-with(., 'h')]]` the same as `//*[starts-with(@*, 'h')]`? – Eric Sep 13 '11 at 21:36
  • 2
    @Eric, Nope. In 2nd XPath node-set passes to `starts-with` function as 1st argument (`@*`). The `starts-with` function converts a node-set to a string by returning the string value of the first node in the node-set, i.e. only 1st attribute. – Kirill Polishchuk Sep 14 '11 at 03:13
  • Shouldn't this use the `contains` function? – nikodaemus Aug 25 '16 at 17:43
14

The general pattern you're looking for is:

@*[contains(., 'string')]

which will match any attribute on the context element that contains string. So if you simply want to search the whole document for attributes containing string, you'd use:

//@*[contains(., 'string')]
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
-1

This is what you are looking for:

//*[@*[starts-with(., 'h')]]