Sample XML input:
<?xml version="1.0"?>
<names>
<name>abc</name>
<name>abc</name>
<name>xyz</name>
<name>def</name>
<name>ghi</name>
</names>
Output needed as:
abc: 2
xyz: 1
def: 1
ghi: 1
Tried below :-
for $n in //names/name return concat($n, ': ', count(//$n))
But output comes like this:
abc: 1
abc: 1
xyz: 1
def: 1
ghi: 1
CodePudding user response:
XPath 3.1 would be
map:merge(
/names/name!map{ string() : .},
map { 'duplicates': 'combine'})
=>
map:for-each(function($k, $v) {
$k || ': ' || count($v)
})
In XPath 2:
for $distinct-name in distinct-values(/names/name)
return concat($distinct-name, ': ', count(/names/name[. = $distinct-name]))