开发者

xslt choosing between select="1" or select="'1'"

What is the difference between <xsl:variable name="test" s开发者_运维技巧elect="1"/>

and <xsl:variable name="test" select="'1'"/> ?

if both results are result tre fragments.. so basically the two lines of code above are identical?

If so. how do we decide which to use?


The first sample creates a variable of type number with the number value 1, the second a variable of type string with the string value "1". Result tree fragments are not created with your code samples, that would be done with <xsl:variable name="test">1</xsl:variable>.


As @Martin pointed out, the first one binds the variable to a number and the second one to a string.

how do we decide which to use?

Think of the use you will do with that variable. For example, in the first case you will be able to do:

item[$test]

This won't be possible in the second case, unless you use number() function.

As per the comments below, string or number will not make any difference when using any of the comparison operators. Even when comparing against nodes sets or rtfs. You can read this on the specs (a bit verbose) or try some silly test.

What still is evident is the different behavior you can obtain when dealing with node positions. For example, if you have:

<xsl:variable name="number2" select="2"/>
<xsl:variable name="string2" select="'2'"/>
<xsl:variable name="rtf2">2</xsl:variable>

and you have the input like this:

<root>
    <test>a</test>
    <test>b</test>
</root>

By using:

    <xsl:value-of select="/root/test[$rtf2]"/>
    <xsl:value-of select="/root/test[$string2]"/>
    <xsl:value-of select="/root/test[$number2]"/>

You will get:

aab

while this:

    <xsl:value-of select="/root/test[position()=$rtf2]"/>
    <xsl:value-of select="/root/test[position()=$string2]"/>
    <xsl:value-of select="/root/test[$number2]"/>

will return:

bbb

due to implicit conversion caused by comparison operators.


XPath 1.0 and XSLT 1.0 treat numbers and strings as pretty much interchangeable, with very few exceptions. A notable exception is item[$test]. But "=" behaves slightly differently too: as numbers 4 and 04 are equal, but as strings they are not.

In XPath 2.0 and XSLT 2.0 the type system is much richer and the difference between strings and numbers is much more noticeable: many operations defined on numbers won't work on strings, and vice-versa.

How to decide? If it's all-numeric, you would normally want to use a number, unless it's something like a phone number, where leading zeros are significant, and it's therefore not really a number but a string of digits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜