substring-before() 関数 | |
最初のパラメータで 2 番目のパラメータが最初に出現する前に、最初のパラメータの部分文字列を返します。最初のパラメータで 2 番目のパラメータが出現しない場合、substring-before() 関数は空の文字列を返します。 | |
入力 | |
2 つの文字列。最初の文字列は検索する文字列で、2 番目の文字列は最初の文字列内で検索する文字列です。 |
|
出力 | |
2 番目のパラメータが最初に出現する前に出現する、最初のパラメータの部分。最初のパラメータで 2 番目のパラメータが出現しない場合、この関数は空の文字列を返します。 |
|
定義先 | |
XPath 4.2 節「文字列関数」 |
|
例 | |
このスタイルシートでは、replace-substring という名前のテンプレートを使用します。また、3 つのパラメータ (元の文字列、元の文字列で検索する部分文字列、および元の文字列で対象となる部分文字列を置き換える部分文字列) を replace-substring テンプレートに渡します。replace-substring テンプレートは、contains()、substring-after()、および substring-before() 関数を拡張して使用します。 サンプルスタイルシートを次に示します。このスタイルシートは、World をすべて文字列 "Mundo" に置き換えます。 <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:variable name="test"> <xsl:call-template name="replace-substring"> <xsl:with-param name="original">Hello World!</xsl:with-param> <xsl:with-param name="substring">World</xsl:with-param> <xsl:with-param name="replacement">Mundo</xsl:with-param> </xsl:call-template> </xsl:variable> <xsl:value-of select="$test"/> </xsl:template> <xsl:template name="replace-substring"> <xsl:param name="original"/> <xsl:param name="substring"/> <xsl:param name="replacement" select="''"/> <xsl:variable name="first"> <xsl:choose> <xsl:when test="contains($original, $substring)"> <xsl:value-of select="substring-before($original, $substring)"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="$original"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="middle"> <xsl:choose> <xsl:when test="contains($original, $substring)"> <xsl:value-of select="$replacement"/> </xsl:when> <xsl:otherwise> <xsl:text></xsl:text> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="last"> <xsl:choose> <xsl:when test="contains($original, $substring)"> <xsl:choose> <xsl:when test="contains(substring-after($original, $substring), $substring)"> <xsl:call-template name="replace-substring"> <xsl:with-param name="original"> <xsl:value-of select="substring-after($original, $substring)"/> </xsl:with-param> <xsl:with-param name="substring"> <xsl:value-of select="$substring"/> </xsl:with-param> <xsl:with-param name="replacement"> <xsl:value-of select="$replacement"/> </xsl:with-param> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="substring-after($original, $substring)"/> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:otherwise> <xsl:text></xsl:text> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:value-of select="concat($first, $middle, $last)"/> </xsl:template> </xsl:stylesheet> このスタイルシートからは、入力として使用される XML ドキュメントとは無関係に、これらの結果が得られます。 Hello Mundo! |