【问题标题】:XSLT: comma separation and custom orderingXSLT:逗号分隔和自定义排序
【发布时间】:2017-10-25 12:48:22
【问题描述】:

我有以下文件(其结构不应更改):

<file>
    <one>First</one>
    <three>Third</three>
    <two>Second</two>
    <five>Fifth</five>
</file>

我正在寻找 XSLT 转换,它提供以下输出(自定义排序 + 逗号分隔):

一、二、三、五

我要手动定义排序:

<xsl:apply-templates select="one">
<xsl:apply-templates select="two">
<xsl:apply-templates select="three">
<xsl:apply-templates select="four">
<xsl:apply-templates select="five">

请注意,原始文件中缺少元素 &lt;four&gt;

不幸的是,常用的逗号分隔方法

<xsl:for-each select="one|two|three|four|five">
    <xsl:value-of select="."/>
    <xsl:if test="position() != last()">, </xsl:if>
</xsl:for-each>

在这种情况下不起作用。当然,我可以使用带有一些排序标准的xsl:sort...

但也许有一个简单而优雅的解决方案,是吗?

【问题讨论】:

  • 好吧,如果您可以使用 XSLT 2 或 3,您可以使用 &lt;xsl:apply-templates select="one, two, three, four, five"/&gt;,然后使用例如您的方法&lt;xsl:template match="file/*"&gt;&lt;xsl:value-of select="."/&gt;&lt;xsl:if test="position() != last()"&gt;, &lt;/xsl:if&gt;&lt;/xsl:template&gt; 可以工作,尽管简单地使用 &lt;xsl:value-of select="one, two, three, four, five" separator=", "/&gt; 更容易。
  • 您愿意详细说明它是如何不起作用的吗?
  • @MartinHonnen 不幸的是,我仅限于 XSLT 1.0。 @Steve for-each 方法的问题在于它忽略了排序(如果我不使用xsl:sort
  • 如果您要询问有关 XSLT 1.0 的问题,请将它们标记为此类。它现在是一种遗留语言变体,我们中的一些人喜欢过滤我们感兴趣的技术。

标签: xml xpath xslt-1.0


【解决方案1】:

如 cmets 中所述,如果您可以使用 XSLT 2.0,您可以这样做......

<xsl:for-each select="one,two,three,four,five">

不过,在 XSLT 1.0 中,一种方法是两个做这样的事情..

    <xsl:for-each select="one|two|three|four|five">
        <xsl:sort select="string-length(substring-before('|one|two|three|four|five|', concat('|', local-name(), '|')))" />

或者,在这种情况下可能稍微简单一些......

    <xsl:for-each select="one|two|three|four|five">
        <xsl:sort select="string-length(substring-before('onetwothreefourfive',local-name()))" />

【讨论】:

    【解决方案2】:

    对于元素onefour,如果元素存在,则需要在其值后面加上逗号,如果元素不存在,则不需要逗号。

    通过在负责的模板中发出逗号很容易处理此问题,因为当且仅当匹配元素存在时才会评估相应的模板。

    我会写

    <xsl:template match="one|two|three|four">
      <xsl:value-of select="string()"/>
      <xsl:text>, </
    </
    <xsl:template match="five">
      <xsl:value-of select="string()"/>
    </
    

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2017-06-22
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多