简体   繁体   中英

XSLT static key declaration using sequence constructor instead of @use?

XSLT2.0 seems to allow declaring key inline, inside the <key> element. All the examples I have seen declare an intermediate XML fragment and match on that, using @use . I think that is wasteful. Can you please provide an example of a XSLT 2.0 key declaration using sequence constructor inside the key element rather than @use ?

Usually the value that you want to index is a very simple function of the objects being indexed, so the @use attribute works perfectly well. You can use a contained sequence constructor for more complex cases if you need to, but I've very rarely seen it needed. For example you might want to index sections by their section number like this:

<xsl:key name="k" match="section">
  <xsl:number level="multi" count="section" format="1.1.1"/>
</xsl:key>

I don't know what makes you think that using the @use attribute is "wasteful".

I don't think I have used that feature so far and I can't think of a good sample for an obvious use case but let's assume foo elements have some value child elements and we want to sort the value elements and only key on the first or last few in sort order so we could use eg

<xsl:key name="by-first-three-values" match="foo">
  <xsl:for-each select="value/xs:decimal(.)">
    <xsl:sort select="."/>
    <xsl:if test="position() lt 4">
      <xsl:sequence select="."/>
    </xsl:if>
  </xsl:for-each>
</xsl:key>

Of course you could avoid that use by writing a function that sorts with perform-sort and then call that function in use="mf:sort(value)[position() lt 4]" but I guess there is at least the flexibility to do it inline of the xsl:key .

What I am after is even more simple, something similar to:

<xsl:key name="AcronymKey" match="a:acronymItem" use="a:acronym"/>

<xsl:template name="AcronymnStandsFor">
    <xsl:param name="acronym"/>
    <!-- change context to current document so the key will work -->
    <xsl:for-each select="document('')">
        <xsl:value-of select="key('AcronymKey',$acronym)/a:standsFor"/>
    </xsl:for-each>
</xsl:template>
<a:acronymList>
    <a:acronymItem>
        <a:acronym>Ant</a:acronym>
        <a:standsFor>Another Neat Tool</a:standsFor>
    </a:acronymItem>

  </a:acronymList>

But where the actual key is inside the key element. Is that possible, given the syntax?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM