Antony
Antony

Reputation: 976

How to pass attribute for parameter using XQUERY

Hi team,

<cars>
     <car id="1">Ford</car>
     <car num="2">Mazda</car>
     <car vol="3">Toyota</car>
     <car soid="4">Lexus</car>
    </cars>

XQuery:

let $val := 1
let $attr := id
return //car[$attr=$val]

I dont know how to pass attribute name in parameter can you please help?

Upvotes: 0

Views: 171

Answers (2)

Michael Kay
Michael Kay

Reputation: 163438

As an alternative, from XQuery 3.0 you have higher-order functions:

let $val := 1
let $attr := function($x){$x!@id}
return //car[$attr(.)=$val]]

Upvotes: 2

Jeroen Mostert
Jeroen Mostert

Reputation: 28789

XQuery is pretty static and doesn't much like dynamic path components. You can leverage local-name():

let $val := 1
let $attr := "id"
return //car[@*[local-name()=$attr and data(.)=$val]]

This is not particularly efficient, though. Work with static expressions when you can, even if this means a repeating a few conditional expressions here and there.

Upvotes: 1

Related Questions