Difference between text() and string()

前端 未结 2 488
醉梦人生
醉梦人生 2020-11-30 07:13

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

2条回答
  •  借酒劲吻你
    2020-11-30 08:05

    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:

    ...
    

    or

    
    

    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() orX/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

    On the wetness of H<sub>2</sub>O
    

提交回复
热议问题