TimJ
TimJ

Reputation: 21

Xquery return the names and values of all child nodes

I'm very new to Xquery and am trying to write a function that takes the names of child nodes (one by one) and compares them against the children of another node (which is always the same), and then where the names are the same, updates the latter with the value from the relevant child of the first.

To start with I just wanted to return all the names and values of the children of the rootnode. I've tried all kinds of things but the below ONLY returns the name and value of the first element of the node.

for $x in $Stored/Rootnode/* let $childnodename:= name($x) let $childnodevalue:= data($x) return distinct-values(concat($childnodename," = ",$childnodevalue ))

Any help would be much appreciated.

Upvotes: 2

Views: 6207

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66783

What you have should be returning all of the name/value items. You are invoking distinct-values() for each child element of Rootnode, rather on the resulting sequence of strings. Moving distinct-values() outside of the FLWOR will dedup the entire set:

let $Stored := 
    <stored>
        <Rootnode>
            <foo>a</foo>
            <bar>b</bar>
            <baz>c</baz>
            <foo>a</foo>
            <bar>b</bar>
            <baz>a</baz>
        </Rootnode>
    </stored>

let $vals :=
    for $x in $Stored/Rootnode/*
    let $childnodename:= name($x)
    let $childnodevalue:= data($x)
    return concat($childnodename," = ",$childnodevalue )

(: dedup name/value strings :)
return distinct-values($vals)

Produces:

foo = a 
bar = b 
baz = c 
baz = a

Upvotes: 2

Related Questions