Alex Rivera | Logout

Difference between text() and string()

Asked 2012-02-29T04:51:26.870
48

Can someone explain the difference between text() and string() functions. I often use one with other, but it does not make any difference, both will get the string value of the xml node.

Edit
Report

1 Answer

12

Most of the time, if you want the content of an element node X, you can refer to it as ".", if it's the context node, or as "X" if it's a child of the context node. For example:

<xsl:if test="X = 'abcd'">...

or

<xsl:value-of select="."/>

In both cases, because the context demands a string, the string() function is applied automatically. (That's a slight simplification, if you're running schema-aware XSLT 2.0 the rules are a little more complicated).

Using string() here is unnecessary, because it's done automatically; and using text() is a mistake (one that seems to be increasingly common, encouraged by some bad tutorials on the web). Using ./text() or X/text() in this situation gives you all the text node children of the element. Often the element has one text node child whose string value happens to be the same as the string value of the element, but your code fails if someone adds a comment or processing instruction, because the value is then split into multiple text nodes. It also fails if the element is one (say title) that allows mixed content: string(title) and title/text() are going to give the same answer until you hit an article with the title

<title>On the wetness of H<sub>2</sub>O</title>
answered 2012-02-29T09:14:09.627

Your Answer