使用XSLT 1.0,如何在如下结构中获取最大数量的不同<info>
元素,它们是同一<container>
元素的子元素(如果可能)?
<root>
<container>
<subelem sometimes_empty='yes'/>
<subelem>
<info>A</info>
</subelem>
<subelem>
<info>B</info>
<irrelevant>meh</irrelevant>
</subelem>
...
</container>
<container>
<subelem>
<info>C</info>
</subelem>
<subelem>
<info>C</info>
</subelem>
...
</container>
...
</root>
使用
here
提供的非重复分组解决方案,我总体上可以获得非重复条目的数量,但实际上我对每个<container>
节点的此数量感兴趣,该数量会更低。我一直在试图将count()和max()函数用于此目的,但是由于对XSLT / XPath的有限经验,我无法成功地这样做。任何帮助将非常感激。
最佳答案
使用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="kContInfo" match="info" use=
"concat(generate-id(ancestor::container[1]),'+',.)"/>
<xsl:template match="/*">
<xsl:for-each select="container">
<xsl:sort data-type="number" order="descending" select=
"count(*/info[generate-id()
=generate-id(key('kContInfo',
concat(generate-id(ancestor::container[1]),
'+',.)
)
)])"/>
<xsl:if test="position() = 1">
<xsl:value-of select=
"count(*/info[generate-id()
=generate-id(key('kContInfo',
concat(generate-id(ancestor::container[1]),
'+',.)
)
)])"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
在提供的XML文档上应用此转换时:
<root>
<container>
<subelem sometimes_empty='yes'/>
<subelem>
<info>A</info>
</subelem>
<subelem>
<info>B</info>
<irrelevant>meh</irrelevant>
</subelem>
...
</container>
<container>
<subelem>
<info>C</info>
</subelem>
<subelem>
<info>C</info>
</subelem>
...
</container>
...
</root>
所需的正确结果产生了:
2
关于xml - 每个节点的最大不同子元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16288880/