0
votes

I have an XML Document of the following Structure.

<Content>
<Function Name="A">
    <SubNode1>
        <SubNode2>
        </SubNode2>
    </SubNode1>
</Function> 
<Function Name="B">
    <SubNode1>
        <SubNode2>
        </SubNode2>
    </SubNode1>
</Function> 
<Function Name="A">
    <SubNode1>
        <SubNode2>
        </SubNode2>
    </SubNode1>
</Function>

Now I want to display all functions with XQuery, using this code.

for $currentFunction in $node where local-name($currentFunction) = 'Function'                       
return
(
    <Function>
    {
       local:printAttributes($currentFunction)
    }
    </Function>
)

This works fine. But I want to display only functions with different Name attributes. It should only show me Function with Name A und the one with Name B, the last function with name A should not be included.

How can i do this? Any suggestions? I'm using XQuery 1.0

1

1 Answers

1
votes

You can use group by to find functions with the same name:

for $func in /Content/Function
let $name := $func/@Name
group by $name
let $last-func := ($func/.)[last()]
return <Function Name="{$name}">{
  local:printAttributes($last-func)
}</Function>

Since the order inside groups is not standardized, you need to use a self step /. in $last-func to sort the elements in document order.

In XQuery 1.0 you can simulate group by by using fn:distinct-values(...):

for $name in distinct-values(/Content/Function/@Name)
let $funcs := /Content/Function[@Name = $name]
let $last-func := $funcs[last()]
return <Function Name="{$name}">{
  local:printAttributes($last-func)
}</Function>