簡體   English   中英

使用 XSL 對名稱和參考 ID 進行排序

[英]Sorting Names and Reference IDs using XSL

如何按字母順序對名稱進行排序? 參考 ID 也應該根據名稱排序進行交換。

例如:

輸入:

<cross-refs id="c0065" refid="b0110 b0190 b0035">Loyal 2018; Anbu 1983; King 2022</cross-refs>

名稱及其 ID

 **Name      --> ReferenceID**
Loyal 2018 --> b0110
Anbu 1983  --> b0190
king 2022  --> b0035

預計 Output:

<cross-refs id="c0065" refid="b0190 b0035 b0110">Anbu 1983; King 2022; Loyal 2018</cross-refs>

我想你可以這樣做:

<xsl:template match="cross-refs">
    <xsl:variable name="refids" select="tokenize(@refid, ' ')" />
    <xsl:variable name="names" select="tokenize(., '; ')" />
    <xsl:variable name="refs">
        <xsl:for-each select="1 to count($refids)">
            <ref refid="{$refids[current()]}" name="{$names[current()]}"/>
        </xsl:for-each>
    </xsl:variable>
    <xsl:variable name="sorted-refs">
        <xsl:perform-sort select="$refs/ref">
            <xsl:sort select="@name"/>
        </xsl:perform-sort>
    </xsl:variable>
    <!-- to output: -->
    <cross-refs id="{@id}">
        <xsl:attribute name="refid" select="$sorted-refs/ref/@refid"/>
        <xsl:value-of select="$sorted-refs/ref/@name" separator="; "/>
    </cross-refs>
</xsl:template>

我想知道是否有人能想出更短的方法。

在 XSLT 3(受當前版本的 Saxon Java、.NET、C、JS 以及 Altova 支持)中,您可以使用

<xsl:template match="cross-refs">
  <xsl:copy>
    <xsl:variable name="ref-map" select="for-each-pair(tokenize(@refid, '\s+'), tokenize(., ';\s*'), function($ref, $name) { map { 'ref' : $ref, 'name' : $name } }) => sort((), function($m) { $m?name })"/>
    <xsl:copy-of select="@id"/>
    <xsl:attribute name="refid" select="$ref-map ! ?ref"/>
    <xsl:value-of select="$ref-map ! ?name" separator="; "/>
  </xsl:copy>
</xsl:template>

XSLT xsl:排序

xsl:sort 元素用於對 output 進行排序。注意:xsl:sort 始終在 xsl:for-each 或 xsl:apply-templates 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM