When should I use /text() at the end of my XPath expression?

3 篇文章 0 订阅
1 篇文章 0 订阅

You have probably seen a lot of examples that use /text() at the end of XPath expressions, and you might be wondering, Should I do the same? Are there any drawbacks?

There are cases in which you do want to append /text() to your XPath expression to force your XQuery to consider the text value of your XPath expression; the typical case is when you want to dynamically create the value of a result element; something like this:

<title>{$doc//book[1]/book-title}</title>

… generates this output:

<title>
<book-title>La Divina Commendia</book-title>
</title>

However, if what you are trying to create is actually this:

<title>La Divina Commendia</title>

… then you need to instruct XQuery to use the text value of the <book-title> element, and an easy way to do that is appending /text() to the XPath expression:

<title>{$doc//book[1]/book-title/text()}</title>

But often XQuery developers use /text() too frequently, in cases similar to this, for example:

for $book in $doc//book[title/text() = "La Divina Commendia"]
return

What are the drawbacks of using /text() when it is not needed? It turns out that there are several:

  • If the data is typed, the type information is thrown away. Beside the possibly unnecessary type conversions, this also makes the query less type safe. This can also cause significant performance disadvantages when dealing with relational data sources.

  • It causes the query to fail — or even produce wrong results — if the element contains comment nodes. There are cases in which this is not true, but in general queries should be written so they aren't affected by comments nodes. Consider the following XQuery, for example:
    let $doc := <root><val>foo<!-- comment -->bar</val></root>
    return
    ($doc//val = "foobar",
    $doc//val/text() = "foobar")

    It returns (true, false) because the result of $doc//val/text() is actually the sequence (“foo”, “bar”) and not “foobar” as you would expect.

  • It makes your queries more verbose than needed

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值