首页 > 解决方案 > 如何在 XSLT/XPath 中解析“/”分隔的字符串?

问题描述

问题如下: 我的 XML 包含内容为“x/y”的元素。这表示进入的“部分”的运行编号。例如,在第一个 XML 中,此元素将具有值 1/5,在第二个中为 2/5,在最后一个中为 5/5。你明白了。元素本身看起来像

<part>x/y</part>

其中 x 可能介于 1 和 y 之间,而 y 可以是任意数字

我需要找到两种情况的答案:

  1. 当 x=1 时,结果应该是“添加”
  2. 当 x=y 时,结果应该是“完成”

如何使用 XSL(1.0 版)解决这个问题?

标签: xmlxsltxslt-1.0

解决方案


使用substring-before()

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

  <xsl:template match="part">
    <xsl:variable name="x" select="substring-before(., '/')"/>
    <xsl:variable name="y" select="substring-after(., '/')"/>
    <xsl:choose>
      <xsl:when test="$x = 1">Add</xsl:when>
      <xsl:when test="$x = $y">Complete</xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="concat('Unexpected values for x,y: ', $x, ',', $y)"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

推荐阅读