您的位置:首页 > 其它

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

2011-12-08 11:11 483 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐