问题 是否有“优雅”的方法来测试属性值以字母开头?


我需要测试一个attibute值是否以字母开头。如果不是,我会用“ID_”作为前缀,因此它将是一个有效的id类型的属性值。 我目前有以下内容(测试该值不以数字开头 - 我知道这些属性值只会以字母或数字开头),但我希望有更优雅的方式:

<xsl:if test="not(starts-with(@value, '1')) and not(starts-with(@value, '2')) and not(starts-with(@value, '3')) and not(starts-with(@value, '4')) and not(starts-with(@value, '5')) and not(starts-with(@value, '6')) and not(starts-with(@value, '7')) and not(starts-with(@value, '8')) and not(starts-with(@value, '9')) and not(starts-with(@value, '0')) ">

我正在使用XSLT 1.0。 提前致谢。


8905
2018-05-12 21:43


起源

XSLT 1.0中的字符串处理操作通常是可行的,但它们很少是优雅的。 - Michael Kay
@Michael - 是的,但这些答案肯定是 更多 比我的优雅! - Jacqueline


答案:


使用

not(number(substring(@value,1,1)) = number(substring(@value,1,1)) )

或者使用

not(contains('0123456789', substring(@value,1,1)))

最后,这可能是最短的XPath 1.0表达式来验证您的状况

not(number(substring(@value, 1, 1)+1))

8
2018-05-13 03:27



很棒的答案 - +1。第三种也是最短的方式是一个很好的转折。永远不会想到这一点。 - Jacqueline
@Jacqueline:是的,XPath是一种令人惊叹的语言,在2.0和3.0版本中更是如此。 - Dimitre Novatchev


它有点短,如果不是非常优雅或明显:

<xsl:if test="not(number(translate(substring(@value, 1, 1),'0','1')))">

基本思想是测试第一个字符是否为数字。该 translate() 需要打电话是因为 0 和 NaN 两者都评价为 false 我们需要 0 被视为 true 里面的 not() 呼叫。


4
2018-05-12 22:33



+1为一个很好的答案。并感谢有关'0'返回false的信息。 - Jacqueline


<xsl:if test="string(number(substring(@value,1,1)))='NaN'">
  1. 使用 substring() 阻止第一个角色 @value 值
  2. 使用 number() 用于评估该角色的功能
    1. 如果字符是数字,则返回一个数字
    2. 如果角色不是数字,它将返回 NaN
  3. 使用 string() 函数将其作为字符串进行评估并检查它是否存在 NaN 或不。

4
2018-05-13 00:38





<xsl:if test="string-length(number(substring(@value,1,1))) > 1">
  1. 使用 substring() 函数来阻止第一个字符 @value 值
  2. 使用 number() 用于评估该角色的功能
    1. 如果字符是数字,则返回一个数字
    2. 如果角色不是数字,它将返回 NaN
  3. 使用 string-length() 评估它是否大于1(不是数字)

0
2018-05-13 00:44