Search code examples
xmlxquerymarklogic

How to handle user-defined arguments in XQuery if these arguments are XML tags/nodes?


so this is basically what I have been struggling with in XQuery,

Assuming I have this XML document

<Library xmlns="http://url.com/lib">
  <Shelf>
   <book>
     Charlie's Chocolate Factory
   </book>
  </Shelf>
</Library>

Then I have this code (Assume whatever is in sequence was what was passed in as an argument, I am assuming that arguments are passed in as strings):

declare namespace lib = "http://url.com/lib";

let $sequence := ("book")
for $arg in $sequence
return //lib:$arg/text())

That code causes an error saying "Unexpected colon." My question is how can I resolve this so that what is returned is simply "Charlie's Chocolate Factory." Let me know if I can be more specific in any way. Thanks for the help in advance!

Clarification EDIT: The question is specifically all about how to handle user-defined arguments assuming these arguments are supposed to refer to element tags (nodes) within the XML document as if we were to do //lib:$arg, that would yield an error. So how do we get around that error? Please assume that "book" is a random user-defined argument. It could be anything like "Library", "Shelf", or maybe even something invalid.


Solution

  • You want //lib:*[local-name()=$sequence]

    Variables in XQuery don't work by textual substitution - you can only use a variable reference where an expression is expected, and that's not in the middle of a name.