【问题标题】:XSLT substring - take all values before specific stringXSLT 子字符串 - 取特定字符串之前的所有值
【发布时间】:2016-12-18 15:04:24
【问题描述】:

我有元素:

<A>11511/direction=sink</A>
<B>110/direction=src</B>

当然,有些元素没有/direction 后缀是很重要的。

如果元素 A 和 B 包含字符串 /direction... 我想要字符串 /direction 之前的值。 如果元素不包含/direction,则照常取常规值。 我应该在value-of 子句中添加什么?

<newElementA><xsl:value-of select="A"/></newElementA>
<newElementB><xsl:value-of select="B"/></newElementB>

我尝试使用 &lt;xsl:value-of select="substring-before(A,'/')"/&gt;,但随后将不具有值 /direction 的值设置为不正确的 null 值

我也试过了,但后来出现错误:

     <newelementA><xsl:value-of select="if (contains(A,'/')) 
then substring-before(A,'/') else A"/></newelementA>

我想在结果中包含值 11511and110

谢谢

【问题讨论】:

  • xslt: substring-before的可能重复
  • 这不是这个问题的重复,因为如果我把 我得到这些元素的空值值中不包含 /direction..,您能帮帮我吗?
  • 您是否仅限于 XSLT 1.0?如果您可以使用 XSLT 2.0 或更高版本,则可以访问比旧的 substring 函数更灵活的正则表达式函数。请说明您可以使用哪个版本的 XSLT。

标签: xml xslt substring


【解决方案1】:

一种可能性是使用条件处理, 和choose 取决于内容的替代操作之间。

例如这个输入(为简单起见仅使用A):

<root>
  <A>11511/direction=sink</A>
  <A>test</A>
</root>

使用此样式表:

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

  <xsl:template match="root">
    <newRoot>
      <xsl:apply-templates select="*"/>
    </newRoot>
  </xsl:template>

  <!-- Create newElementA -->
  <xsl:template match="A">
    <newElementA>
      <xsl:call-template name="chooseContent"/>
    </newElementA>
  </xsl:template>

  <!-- Reusable template to determine element content -->
  <xsl:template name="chooseContent">
    <xsl:choose>
      <xsl:when test="contains(.,'/direction')">
        <xsl:value-of select="substring-before(.,'/direction')"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="."/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- Ignore unknown elements -->
  <xsl:template match="*"/>
</xsl:stylesheet>

结果:

<newRoot>
  <newElementA>11511</newElementA>
  <newElementA>test</newElementA>
</newRoot>

【讨论】:

    【解决方案2】:

    如果您可以使用 XSLT 2.0 或更高版本,正则表达式函数 replace 可为您提供所需的灵活性。

    例子:

    <xsl:value-of select="replace(., '(.*?)/.*$', '$1')"/>
    

    我已经确认,这会为任何字符串 1235sdfa/sdff93rjdf 以及任何不包含 / 的字符串 asda98273jasdf 生成您想要的输出。

    【讨论】:

    • 啊,是的,它可以这么简单。希望 XSLT 2.0 在不久的将来能得到更广泛的支持。
    • @Meyer -- 如果您使用的是 Microsoft XML 库,不要指望 XSLT 2.0 很快就会出现。
    • 哦,好吧。我主要使用 libxml2 绑定到 Linux,XSLT 2.0 似乎同样不太可能。因此,我对老式便携式 1.0 的回答是。
    猜你喜欢
    • 2011-03-07
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2014-05-22
    相关资源
    最近更新 更多