XSLT: select distinct but slightly different to other examples

喜欢而已 提交于 2019-12-11 02:26:36

问题


I have the following XML:

<a>
    <b>
        <d>D1 content (can include child nodes)</d>
    </b>
    <b>
        <c>C1 content (can include child nodes)</c>
    </b>
    <b>
        <e>E1 content (can include child nodes)</e>
    </b>
    <b>
        <c>C2 content (can include child nodes)</c>
    </b>
</a>

Using XSLT 1.0, I need to produce from this simply: "cde"; i.e. a distinct list of the names of the immediate children of /a/b/ ordered by the node name. Each b has exactly one child of arbitrary name.

I can produce "ccde":

<xsl:for-each select="/a/b/*">
    <xsl:sort select="name(.)"/>
    <xsl:value-of select="name(.)" />
</xsl:for-each>

I've tried using the usual preceding-sibling:: comparison, but as each b only has one child, the preceding sibling is always nothing.


回答1:


First add this key element to the top of your XSL:-

<xsl:key name="tagNames" match="/a/b/*" use="name()" /> 

Now your for each loop can look like this:-

<xsl:template match="/*">
    <xsl:for-each select="/a/b/*[count(. | key('tagNames', name())[1]) = 1]">
        <xsl:sort select="name()" />
        <xsl:value-of select="name()" />
    </xsl:for-each>
</xsl:template>



回答2:


You can use Muenchian method:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="groupIndex" match="*" use="name()" />
    <xsl:template match="/">
        <xsl:apply-templates select="a/b"/>
    </xsl:template>
    <xsl:template match="b">
        <xsl:apply-templates select="*[1][generate-id(.) = generate-id(key('groupIndex', name())[1])]" mode="group" />
    </xsl:template>
    <xsl:template match="*" mode="group">
        <xsl:value-of select="name()"/>
    </xsl:template>
</xsl:stylesheet>


来源:https://stackoverflow.com/questions/1813286/xslt-select-distinct-but-slightly-different-to-other-examples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!