如何比较xslt中的多个字符串

Lam*_*mps 15 xml xslt

为了将xml字符串值与多个字符串进行比较,我将执行以下操作.

<xsl:if test="/Lines/@name = 'John' or /Lines/@name = 'Steve' or /Lines/@name = 'Marc' " >
Run Code Online (Sandbox Code Playgroud)

可以任何人告诉我,而不是在上面的情况下使用'或',我如何使用xslt检查字符串是否存在于一组字符串中.

谢谢.

Dim*_*hev 21

三种方法:

  1. 使用管道(或其他适当的字符)分隔的字符串

...

 <xsl:template match=
  "Lines[contains('|John|Steve|Mark|',
                  concat('|', @name, '|')
                 )
         ]
  ">
     <!-- Appropriate processing here -->
 </xsl:template>
Run Code Online (Sandbox Code Playgroud)

0.2.针对外部传递的参数进行测试.如果参数没有在外部设置,并且我们使用的是XSLT 1.0,则xxx:node-set()需要使用扩展函数将其转换为普通节点集,然后再访问其子节点

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <!-- externally-specified parameter -->
 <xsl:param name="pNames">
  <n>John</n>
  <n>Steve</n>
  <n>Mark</n>
 </xsl:param>

 <xsl:template match="Lines">
  <xsl:if test="@name = $pNames/*">
     <!-- Appropriate processing here -->
    </xsl:if>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

0.3.在XSLT 2.0中比较一系列字符串

 <xsl:template match="Lines[@name=('John','Steve','Mark')]">
     <!-- Appropriate processing here -->
 </xsl:template>
Run Code Online (Sandbox Code Playgroud)

  • +1为真正收缩的XSLT 1.0解决方案(#1)。 (2认同)

Mar*_*nen 9

仅限XSLT 2.0: <xsl:if test="/Lines/@name = ('John', 'Steve', 'Marc')">

使用XSLT 1.0,您无法编写表示字符串序列或一组字符串的文字表达式,但如果您知道文字值,则可以构建一组节点,例如

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0"
  xmlns:data="http://example.com/data"
  exclude-result-prefixes="data">

  <data:data xmlns="">
    <value>John</value>
    <value>Steve</value>
    <value>Marc</value>
  </data:data>

  <xsl:variable name="values" select="document('')/xsl:stylesheet/data:data/value"/>

  <xsl:template match="...">
     <xsl:if test="/Lines/@name = $values">..</xsl:if>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)