Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xs:string as element() in XQuery

Tags:

xpath

xquery

Let's assume I have a XML files, one like this:

<SampleF>
  <FirstNode AAA="Something" BBB="Something"></FirstNode>
  <SecondNode CCC="Random" DDD="Random"></SecondNode>
</SampleF>

And second one like this:

<SampleF2>
  <FirstNode>
    <AAA>Something</AAA>
    <BBB>Random</BBB>
  </FirstNode>
</SampleF2>

And I would like to obtain from both (AAA="Something"/Something) of them as element(). How do I convert it? When in first case I get xs:string and in the second document-node().

I made something like this for the first example but I'm 100% certain there is a better way of doing this

declare function getElementFirstExample($message) as element() {
let $name := "AAA"
let $value := $message/*:SampleF1/*:FirstNode/@AAA
return element {$name} {"$value"}
};

Thank you in advance for your help and advices.

like image 372
Mateusz Chrzaszcz Avatar asked Jun 11 '26 06:06

Mateusz Chrzaszcz


1 Answers

As I understand, you want the value of <FirstNodes/>s AAA attribute or child element, no matter whether it is in the element or attribute.

Use an alternative axis step for accessing both the attribute and element, and data(...) to retrieve the string value.

data(//FirstNode/(@AAA, AAA))

Putting this together for your function and explicit use case:

declare function getElementFirstExample($message) as element() {
  let $name := "AAA"
  let $value := data($message/*:SampleF1/*:FirstNode/(@AAA, *:AAA))
  return element {$name} {"$value"}
};
like image 143
Jens Erat Avatar answered Jun 19 '26 14:06

Jens Erat