Greg
Greg

Reputation: 21909

XPath query for matching any attribute with name starting with X

From this Stack Overflow answer, I can see how to match on any attribute values that start with a particular string. For example, finding a list of elements that have any attribute with a value starting with the letter h:

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

My question is how to match attribute names that start with a particular string?

As I understand it, the @* indicates matching any attribute within the wider //* collection of any elements. The starts-with function takes two parameters, the haystack and the needle, and the . haystack indicates the attribute value. I feel like I'm 90% of my way there, but I can't figure out what I need to match on the attribute name, rather than value.

Example matches:

<example>
    <first match-me="123">MATCH!</first>
    <second do-not-match-me="456">NO MATCH!</second>
    <third match-me-yes-please="789">MATCH!</third>
    <fourth>
        <fifth match-me:oh-yes>MATCH!</fifth>
    </fourth>
</example>

Upvotes: 3

Views: 910

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

"I feel like I'm 90% of my way there" - yes, the last phase is specifying attribute name method:

//*[@*[starts-with(name(), 'match-me')]]

Note, relying on simple attribute name matching you may encounter an issue when dealing with attribute names like match-me:oh-yes (colon inside). In such cases, you'll probably get an error The prefix "match-me" for attribute "match-me:oh-yes" associated with an element type "fifth" is not bound OR Attribute name "match-me:oh-yes" associated with an element type "fifth" must be followed by the ' = ' character.(in case of "valueless" attribute)

Upvotes: 4

Related Questions