Re: [xsl] When to use text()

Subject: Re: [xsl] When to use text()
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxx>
Date: Fri, 21 Mar 2014 10:20:22 -0400
Hi,

To gloss Mike ...

Yes, text() is over-used and commonly misused.

If you need to be sure you have a string, the way to do that is with a
function for the purpose, such as string().

The irony is that those who use text() to get a string, aren't getting
a string ... they're getting a text node (or sequence of text nodes)
that must still be cast to a string as necessary.

Most of the time, what is wanted is easily achieved using . (i.e.
self::node()) and avoiding text() ...

So, substring(.,2) returns the string value of the context node
starting with the second character, while substring(text(),2) returns,
*at best*, the same thing, or if not, an error (under XSLT 2.0) or
some other substring, not wanted (under 1.0). This is easily
demonstrated with examples such as the one Mike gave.

What's worse, the errors will be rare -- the kind that can easily get
past testing, especially by developers who are not familiar with the
vagaries of documentary data, where information can take forms they do
not expect. If you've never seen mixed content, comments or processing
instructions in your XML, you may never have had to think about what
will or should happen when you do.

Cheers, Wendell

On Fri, Mar 21, 2014 at 7:37 AM, Michael Kay <mike@xxxxxxxxxxxx> wrote:
>
> On 21 Mar 2014, at 11:08, Heiko Niemann <kontakt@xxxxxxxxxxxxxxxx> wrote:
>
>> Hi,
>>
>> I noticed in my code that I sometimes use text() to select a text node and
>> sometimes I don't. I do understand that /foo is different to /foo/text()
>> if foo has mixed content. But if I have a simple source like
>>
>> <box>
>>  <item>apple</item>
>> </box>
>
> In such content you should NOT use text(). If you do, your code will fail in the presence of comments such as
>
> <item>appel<!--sic--> pie</item>
>
> and it's good practice that comments should not affect the result of processing.
>
>> So this leaves the question: when actually use text()?
>>
>
> Only use it if you need to process the text node children and element children of a mixed-content element individually.
>
> Michael Kay
> Saxonica
>



-- 
Wendell Piez | http://www.wendellpiez.com
XML | XSLT | electronic publishing
Eat Your Vegetables
_____oo_________o_o___ooooo____ooooooo_^

Current Thread