Is there an “elegant” way to test that an attribut

2019-02-08 16:28发布

I need to test whether an attibute value starts with a letter. If it doesn't I'll prefix it with "ID_" so it will be a valid id type of attribue value. I currently have the following (testing that the value does not start with a number - I know these attribute values will only start with a letter or number), but I am hoping there is an more elegant way:

<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')) ">

I'm using XSLT 1.0. Thanks in advance.

标签: xslt xpath
4条回答
ゆ 、 Hurt°
2楼-- · 2019-02-08 17:16
<xsl:if test="string(number(substring(@value,1,1)))='NaN'">
  1. Use substring() to snag the first character from the @value value
  2. Use the number() function to evaluate that character
    1. If the character is a number, it will return a number
    2. If the character is not a number it will return NaN
  3. Use the string() function to evaluate that as a string and check to see if it is NaN or not.
查看更多
Evening l夕情丶
3楼-- · 2019-02-08 17:24
<xsl:if test="string-length(number(substring(@value,1,1))) > 1">
  1. Use the substring() function to snag the first character from the @value value
  2. Use the number() function to evaluate that character
    1. If the character is a number, it will return a number
    2. If the character is not a number it will return NaN
  3. Use string-length() to evaluate whether it was greater than 1 (not a number)
查看更多
Rolldiameter
4楼-- · 2019-02-08 17:25

Use:

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

Or use:

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

Finally, this may be the shortest XPath 1.0 expression to verify your condition:

not(number(substring(@value, 1, 1)+1))
查看更多
beautiful°
5楼-- · 2019-02-08 17:33

It's a bit shorter, if not exactly elegant or obvious:

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

The basic idea is to test whether the first character is a digit. The translate() call is needed because 0 and NaN both evaluate to false and we need 0 to be treated as true inside of the not() call.

查看更多
登录 后发表回答