WyllianNeo
WyllianNeo

Reputation: 363

How return multiple tags inside a if/else using XQuery?

I have to do something like:

declare function xf:NameOfXQ($myIn as element(ns2:myIn))
    as element() {
        <ns0:tagIn>

            <myObj>
               {
                for $var in $myValueOfVar
                    return
                        if ($var= "X") then
                            <tagA>A</tagA>
                            <tagB>B</tagB>
                            <tagC>C</tagC>
                        else
                            <tagD>D</tagD>
                }
            </myObj>

        </ns0:tagIn>
};

But when the xquery is build, my project says "Invalid expression, expecting ELSE, found '>'" I try then use 4 IF's, one to fill each tag, like:

declare function xf:NameOfXQ($myIn as element(ns2:myIn))
    as element() {
        <ns0:tagIn>

            <myObj>
            {
            for $var in $myValueOfVar
                return
                    if ($var= "X") then
                        <tagA>A</tagA>
                    else
                        ()
                    if ($var= "X") then
                        <tagB>B</tagB>
                    else
                        ()
                    if ($var= "X") then
                        <tagC>C</tagC>
                    else
                        ()
                    if ($var != "X") then
                        <tagD>D</tagD>
                    else
                        ()
            }
            </myObj>

        </ns0:tagIn>
};

Then my project says "Invalid expression: unexpected token: if" How I can do it correctly?

Upvotes: 3

Views: 1449

Answers (1)

Aaron
Aaron

Reputation: 24812

XQuery doesn't consider multiple consecutive tags as syntactically correct, an XML fragment must have a root tag to be valid.

It however allows you to use sequence types with the syntax (item1, item2, ... itemN) which you can use to let the return clause of your FLWOR expression yield multiple XML tags :

for $var in $myValueOfVar
    return
        if ($var= "X") then
            (
                <tagA>A</tagA>,
                <tagB>B</tagB>,
                <tagC>C</tagC>
            )
        else
            <tagD>D</tagD>

Upvotes: 3

Related Questions