Search code examples
xmlxpath

Finding unique values with their occcrrences in XPath 2.0 or 3.0


I have following XML

<Root>
    <Email>
        <Key> 1</Key>
    </Email>
    <Email>
        <Key> 1</Key>
    </Email>
    <Email>
        <Key> 2</Key>
    </Email>
    <Email>
        <Key> 2</Key>
    </Email>
    <Email>
        <Key> 3</Key>
    </Email>
</Root>

I am using XPATH 2.0 and can use XPATH 3.0 as well. I need unqiue values for Key along with their occcurences. So I need following output.

1 (2 time), 2 (2 time), 3 (1 time)

I tried string-join(distinct-values(//Key) , ' ') function in XPATH 2.0 but I get only following from it

1 2 3

I am missing the occcurrences, tried using count function in string join but string join expects a separator as second input.


Solution

  • XPath has limitations. It cannot compose new constructs. For that you need to use XQuery.

    Please try along the following.

    XPath 2.0

    for $x in distinct-values(/Root/Email/Key)
    return concat($x, " - (", count(/Root/Email/Key[text()=$x]), " times)")
    

    Output

    1 - (2 times)
    2 - (2 times)
    3 - (1 times)