XSLT字符串拼接,去除最后一个逗号

29

我需要使用XSLT构建一个字符串,并在每个字符串之间用逗号分隔,但是不要在最后一个字符串后包含逗号。例如,在我的示例中,如果我有分发节点而不是注释节点,那么我将具有尾随逗号。我不知道在XSLT中构建变量并截断最后一个字符的任何方法。另外,这是使用微软XSLT引擎。

我的字符串 =

<xsl:if test="Locality != ''">
  <xsl:value-of select="Locality"/>,
</xsl:if>
<xsl:if test="CollectorAndNumber != ''">
  <xsl:value-of select="CollectorAndNumber"/>,
</xsl:if>
<xsl:if test="Institution != ''">
  <xsl:value-of select="Institution"/>,
</xsl:if>
<xsl:if test="Distribution != ''">
  <xsl:value-of select="Distribution"/>,
</xsl:if>
<xsl:if test="Note != ''">
  <xsl:value-of select="Note"/>
</xsl:if>

[哎呀,一定有更好的方法输入文字到这个问题文本框中 :( ]


2
@Craig:就我个人而言,我认为SO文本编辑器是我使用过的最好的一个(至少是基于Web的)。你不喜欢它的哪些方面呢? - Welbog
1
@Weblog 我基本上同意你的观点。但有一个例外,就是当SO代码编辑器将XPath中的谓词(如myElem[1])视为超链接并将它们更改为类似于myElem[5]的内容时,这是一个非常讨厌的错误,具体取决于文本中已经存在多少真正的链接。 - Dimitre Novatchev
6个回答

53

使用XSLT非常容易实现这一点不需要将结果捕获到变量中,也不需要使用特殊的命名模板):

I. XSLT 1.0:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

    <xsl:template match="/*/*">
      <xsl:for-each select=
      "Locality/text() | CollectorAndNumber/text()
     | Institution/text() | Distribution/text()
     | Note/text()
      "
      >
        <xsl:value-of select="."/>
        <xsl:if test="not(position() = last())">,</xsl:if>
      </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

当应用此转换器于以下 XML 文档时:

<root>
    <record>
        <Locality>Locality</Locality>
        <CollectorAndNumber>CollectorAndNumber</CollectorAndNumber>
        <Institution>Institution</Institution>
        <Distribution>Distribution</Distribution>
        <Note></Note>
        <OtherStuff>Unimportant</OtherStuff>
    </record>
</root>

产生了所需的结果:

Locality,CollectorAndNumber,Institution,Distribution

如果需要产生的元素不按文档顺序排序(这是问题中没有要求的,但被Tomalak提出),仍然可以轻松而优雅地实现:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:param name="porderedNames"
     select="' CollectorAndNumber Locality Distribution Institution Note '"/>

    <xsl:template match="/*/*">
        <xsl:for-each select=
         "*[contains($porderedNames, concat(' ',name(), ' '))]">

         <xsl:sort data-type="number"
          select="string-length(
                     substring-before($porderedNames,
                                      concat(' ',name(), ' ')
                                      )
                                )"/>

            <xsl:value-of select="."/>
            <xsl:if test="not(position() = last())">,</xsl:if>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

在这里,所需元素的名称及其顺序以字符串参数$porderedNames的形式提供,其中包含所有所需名称的以空格分隔的列表。

当上述转换应用于同一XML文档时,将产生所需的结果:

CollectorAndNumber,Locality,Distribution,Institution

II. XSLT 2.0:

XSLT中这个任务甚至更简单(同样不需要使用特殊函数):

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

    <xsl:template match="/*/*">
    <xsl:value-of separator="," select=
    "(Locality, CollectorAndNumber,
     Institution, Distribution,
     Note)[text()]" />
    </xsl:template>
</xsl:stylesheet>

对同一份 XML 文档应用这个转换时,能够获得相同正确的结果:

Locality,CollectorAndNumber,Institution,Distribution

请注意,由于我们使用XPath 2.0序列类型(而不是XSLT 1.0解决方案中的联合),所以所需元素将按任意顺序生成,根据定义,该序列类型包含按任意(指定)顺序排列的项目。


这难道不意味着在XSLT 1.0输出中有文档顺序吗?我故意使用变量来自由地按照我喜欢的方式排序输出。 - Tomalak
@Tomalak,从问题中并不清楚,而且在提供的XML文档中,文档顺序与所需顺序匹配。如果需要不同的输出顺序,请注意XSLT 2.0解决方案不依赖于文档顺序。对于一个独立于文档顺序的XSLT 1.0解决方案,我更喜欢在某个参数中给出元素名称列表--然后仍然可以有一个单独的xsl:for-each或<xsl:template。然而,这超出了原始问题的范围。我更喜欢在另一个问题中提供这个问题,然后我会提供所描述的解决方案。 - Dimitre Novatchev
我被XSLT 1.0卡住了,但你解决了它。谢谢。对你的方法的改进是将IF修改为'<xsl:if test="(. != '') and (position() != last())">'。 - Craig
@Craig 实际上,这并不需要。如果文本长度为零,则 text() 的测试不会成功。 - Dimitre Novatchev
@Dimitre Novatchev:虽然原问题中没有指定自定义顺序,但我认为这并不是太牵强。事实上,你的两个1.0解决方案都很好。我本来会发布你的XSLT 1.0解决方案#1(毕竟它很明显),但文档顺序独立对我很重要。对于XSLT 1.0解决方案#2和XSLT 2.0变体,给予+1的支持。 - Tomalak

7
我希望有一个简短的调用模板将节点值连接在一起。如果你的连接列表中间缺少一个节点,例如Institution,这也可以工作:
<xsl:template name="join">
    <xsl:param name="list" />
    <xsl:param name="separator"/>

    <xsl:for-each select="$list">
        <xsl:value-of select="." />
        <xsl:if test="position() != last()">
            <xsl:value-of select="$separator" />
        </xsl:if>
    </xsl:for-each>
</xsl:template>

我可以帮助您进行翻译。以下是一个使用它的简短示例:

样本输入文档:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
    <Locality>locality1</Locality>
    <CollectorAndNumber>collectorAndNumber1</CollectorAndNumber>
    <Distribution>distribution1</Distribution>
    <Note>note1</Note>
  </item>
  <item>
    <Locality>locality2</Locality>
    <CollectorAndNumber>collectorAndNumber2</CollectorAndNumber>
    <Institution>institution2</Institution>
    <Distribution>distribution2</Distribution>
    <Note>note2</Note>
  </item>
  <item>
    <Locality>locality3</Locality>
    <CollectorAndNumber>collectorAndNumber3</CollectorAndNumber>
    <Institution>institution3</Institution>
    <Distribution>distribution3</Distribution>
  </item>
</items>

XSL转换:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <summary>
      <xsl:apply-templates />
    </summary>
  </xsl:template>

  <xsl:template match="item">
    <item>
      <xsl:call-template name="join">
        <xsl:with-param name="list" select="Locality | CollectorAndNumber | Institution | Distribution | Note" />
        <xsl:with-param name="separator" select="','" />
      </xsl:call-template>
    </item>
  </xsl:template>

  <xsl:template name="join">
    <xsl:param name="list" />
    <xsl:param name="separator"/>

    <xsl:for-each select="$list">
      <xsl:value-of select="." />
      <xsl:if test="position() != last()">
        <xsl:value-of select="$separator" />
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

生成的输出文档:
<?xml version="1.0" encoding="utf-8"?>
<summary>
  <item>locality1,collectorAndNumber1,distribution1,note1</item>
  <item>locality2,collectorAndNumber2,institution2,distribution2,note2</item>
  <item>locality3,collectorAndNumber3,institution3,distribution3</item>
</summary>

注意:如果您使用的是XSLT / XPath 2.0,则会有fn:string-join

fn:string-join**($operand1 as string*, $operand2 as string*) as string

可以按以下方式使用:

fn:string-join({Locality, CollectorAndNumber, Distribution, Note}, ",") 

你的答案和Dimitre的差不多。不过他的稍微更加优雅。谢谢。 - Craig

3

假设您有以下输入XML:

<root>
  <record>
    <Locality>Locality</Locality>
    <CollectorAndNumber>CollectorAndNumber</CollectorAndNumber>
    <Institution>Institution</Institution>
    <Distribution>Distribution</Distribution>
    <Note>Note</Note>
    <OtherStuff>Unimportant</OtherStuff>
  </record>
</root>

那么这个模板就可以做到:
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

  <xsl:output method="text" />

  <xsl:template match="record">
    <xsl:variable name="values">
      <xsl:apply-templates mode="concat" select="Locality" />
      <xsl:apply-templates mode="concat" select="CollectorAndNumber" />
      <xsl:apply-templates mode="concat" select="Institution" />
      <xsl:apply-templates mode="concat" select="Distribution" />
      <xsl:apply-templates mode="concat" select="Note" />
    </xsl:variable>

    <xsl:value-of select="substring($values, 1, string-length($values) - 1)" />
    <xsl:value-of select="'&#10;'" /><!-- LF -->
  </xsl:template>

  <xsl:template match="Locality | CollectorAndNumber | Institution | Distribution | Note" mode="concat">
    <xsl:value-of select="." />
    <xsl:text>,</xsl:text>
  </xsl:template>

</xsl:stylesheet>

我的系统输出:

Locality,CollectorAndNumber,Institution,Distribution,Note

我编辑了我的答案,提供了任意列表和元素排序的解决方案,正如你所建议的。谢谢! - Dimitre Novatchev

2

我认为提一下可能会有帮助,当我使用一个复杂的选择器来过滤一些节点时,position()函数不能正常工作。在这种情况下,我想到了以下技巧:

你可以定义一个字符串变量,用特定字符分隔节点的值,然后通过使用str:tokenize()函数,你可以创建一个完整的节点列表,其中position()函数可以正常工作。

类似这样:

<!-- Since position() doesn't work as expected(returning node position of current 
node list), I got round it by a string variable and tokenizing it in which 
absolute position is equal to relative(context) position. -->
<xsl:variable name="measObjLdns" >
    <xsl:for-each select="h:measValue[@measObjLdn=$currentMeasObjLdn]/h:measResults" >
        <xsl:value-of select="concat(.,'---')"/> <!-- is an optional separator. -->
    </xsl:for-each>
</xsl:variable>

<xsl:for-each select="str:tokenize($measObjLdns,'---')" ><!-- Since position() doesn't 

work as expected(returning node position of current node list), 
I got round it by a string variable and tokenizing it in which
absolute position is equal to relative(context) position. -->

    <xsl:value-of select="."></xsl:value-of>
    <xsl:if test="position() != last()">
        <xsl:text>,</xsl:text>
    </xsl:if>
</xsl:for-each>
<xsl:if test="position() != last()">
    <xsl:text>,</xsl:text>
</xsl:if>

解释你的代码可能有助于重用它。我有一个类似的过滤节点的问题。但是在一天结束时,我仍然无法理解你的答案,尤其是在与XSLT的怪癖斗争。 :-) - GuruM

1

你没有一个始终存在的值吗?如果有,那么你可以将其反转,并在除第一项(始终存在的值)之外的所有项目前加上逗号。


-4

如果只有像你的例子中那样少量的元素,这可能会有点混乱,但可能会起作用:

<xsl:if test="Locality != ''">
    <xsl:value-of select="Locality"/>
    <xsl:if test="CollectorAndNumber != '' or Institution != '' or Distribution != '' or Note != ''">
        <xsl:value-of select="','"/>
    </xsl:if>
</xsl:if>
<xsl:if test="CollectorAndNumber != ''">
    <xsl:value-of select="CollectorAndNumber"/>
    <xsl:if test="Institution != '' or Distribution != '' or Note != ''">
        <xsl:value-of select="','"/>
    </xsl:if>
</xsl:if>
<xsl:if test="Institution != ''">
    <xsl:value-of select="Institution"/>
    <xsl:if test="Distribution != '' or Note != ''">
        <xsl:value-of select="','"/>
    </xsl:if>
</xsl:if>
<xsl:if test="Distribution != ''">
    <xsl:value-of select="Distribution"/>
    <xsl:if test="Note != ''">
        <xsl:value-of select="','"/>
    </xsl:if>
</xsl:if>
<xsl:if test="Note != ''">
    <xsl:value-of select="Note"/>
</xsl:if>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接