使用XSLT 1.0,如何在如下结构中(如果可能的话)获得作为同一<container>
元素的子元素的不同<info>
元素的最大数量?
<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
您引用的链接是正确的方向。在本例中,您只需要一个像这样的组合键:
<xsl:key
name="kInfoByContainer"
match="info"
use="concat(generate-id(../../container), '+', .)" />
确认一下,当这个XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="no" indent="yes" method="text"/>
<xsl:strip-space elements="*"/>
<xsl:key
name="kInfoByContainer"
match="info"
use="concat(generate-id(../../container), '+', .)"/>
<xsl:template match="container">
Container <xsl:value-of select="position()"/> has unique info elements:
<xsl:value-of
select="count(*/info[generate-id() =
generate-id(key(
'kInfoByContainer',
concat(generate-id(../../container), '+', .)
)[1])])"/>
</xsl:template>
</xsl:stylesheet>
…
<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>
…生成所需的结果:
Container 1 has unique info elements:
2
Container 2 has unique info elements:
1