kaboom
kaboom

Reputation: 833

XQuery nested for clause

I kept getting this error in XQuery, but I was sure that I opened and closed the brackets. What may go wrong with this query?

XPST0003 XQuery syntax error near #...{ $x/name }</name> {for#:
    expected "}", found "{"

This is the query

  <myquery>
        <A>

        {for $x in doc("example.xml")/example/A
        where $x/name = "United States" 
        return 
            <name>{ $x/name }</name> (: error reported at this line of code :)

            {for $y in $x/B
            let $z := $y/C div $y/D
            order by $z
            return
                <B>
                    <C>{$y/name/text()}</C>
                    <ratio>{ $z }</ratio>
                </B>
            }
        }

    </A>
</myquery>

Upvotes: 0

Views: 958

Answers (1)

Jens Erat
Jens Erat

Reputation: 38682

Given you want to return the name tags followed by B tags, you will have to return a sequence:

<myquery>
    <A>{
        for $x in doc("example.xml")/example/A
        where $x/name = "United States"
        return (                        (: Return a sequence here :)
            <name>{ $x/name }</name>,   (: Be aware of the comma :)

            for $y in $x/B
            let $z := $y/C div $y/D
            order by $z
            return
                <B>
                    <C>{$y/name/text()}</C>
                    <ratio>{ $z }</ratio>
                </B>
        )                               (: end of sequence :)
    }</A>
</myquery>

I also removed the unnecessary curly brackets around the FLWOR expression, and be aware I added a comma after the name tag.

Upvotes: 1

Related Questions