XSLT substring - 在特定字符串之前获取所有值

时间:2016-12-18 15:04:24

标签: xml xslt substring

我有元素:

<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>

我尝试使用<xsl:value-of select="substring-before(A,'/')"/>,但是没有值/direction的值设置为值null,这是不正确的

我也尝试了这个,但后来收到了错误:

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

我希望结果中包含值11511110

由于

2 个答案:

答案 0 :(得分:2)

一种可能性是使用条件处理, 和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>

答案 1 :(得分:1)

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

示例:

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

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