[英]How to count elements with same name? XML -> Xquery
i have a xml doc like: 我有一个XML文档,如:
<root>
<test>
<humans>
<names>Tim</names>
</humans>
</test>
<test>
<humans>
<names>Jack</names>
<names>Jones</names>
</humans>
</test>
<test>
<humans>
<names>Tim</names>
</humans>
</test>
</root>
and I want to count all names which are the same: Tim 2, Jack 1, Jones 1 and it should give an output like: 我想计算所有相同的名字:Tim 2,Jack 1,Jones 1,它应该给出如下输出:
<x> Tim </x>
because TIM is the highest name 因为TIM是最高的名字
I hope you can help me... (sorry for my bad english) 我希望你能帮助我...(对不起我的英语不好)
In XPath 2.0, XSLT 2.0 and XQuery use (exactly the same solution): 在XPath 2.0中,使用XSLT 2.0和XQuery (完全相同的解决方案):
(/*/*/*/names[for $v in .,
$cnt in count(/*/*/*/names[. eq $v])
return
$cnt
eq
max(for $n in distinct-values(/*/*/*/names)
return
count(/*/*/*/names[. eq $n])
)
]
)[1]
You can also get this element easily with the following XSLT 1.0 transformation : 您还可以通过以下XSLT 1.0转换轻松获得此元素 :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kNamesByVal" match="names" use="."/>
<xsl:template match="/">
<xsl:for-each select=
"*/*/*/names[generate-id()
=
generate-id(key('kNamesByVal',.)[1])
]">
<xsl:sort select="count(key('kNamesByVal',.))"
data-type="number" order="descending"/>
<xsl:if test="position()=1">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
When the above XPath 2.0/XQuery expression or XSLT transformation are evaluated (applied) on the provided XML document : 在提供的XML文档中评估(应用)以上XPath 2.0 / XQuery表达式或XSLT转换时 :
<root>
<test>
<humans>
<names>Tim</names>
</humans>
</test>
<test>
<humans>
<names>Jack</names>
<names>Jones</names>
</humans>
</test>
<test>
<humans>
<names>Tim</names>
</humans>
</test>
</root>
the correct element is selected (produced): 选择(产生)了正确的元素:
<names>Tim</names>
let $xml := <!-- your xml document -->
return
(
for $name in distinct-values($xml//names)
order by count($xml//names[. = $name]) descending
return <x>{$name}</x>
)[1]
The solution of Gunther is the best, and if you wanted to count every elements you could do: 贡瑟(Gunther)的解决方案是最好的,如果您想计算每个元素,您都可以做到:
xquery version "1.0";
for $x in
(
for $name in distinct-values(//names)
order by count(//names[. = $name]) descending
return <x>{$name}</x>
) return fn:concat($x, ' - ',xs:string(count(//names[. = $x])))
With result Tim - 2 Jack - 1 Johons - 1 结果Tim-2 Jack-1 Johons-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.