Xpath to search for a node that has ANY attribute containing a specific string?
Asked Answered
M

3

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

Melodimelodia answered 13/9, 2011 at 16:24 Comment(1)
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"?Ankerite
I
23

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')]]
Iodic answered 13/9, 2011 at 16:47 Comment(3)
Is //*[@*[starts-with(., 'h')]] the same as //*[starts-with(@*, 'h')]?Macerate
@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.Iodic
Shouldn't this use the contains function?Bigener
K
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')]
Kylie answered 13/9, 2011 at 17:10 Comment(1)
Short and sweetBigener
A
-1

This is what you are looking for:

//*[@*[starts-with(., 'h')]]
Adolfoadolph answered 5/5, 2020 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.