zoukankan      html  css  js  c++  java
  • [xpath] text()和string()区别

    质区别

    text()是一个node test,而string()是一个函数,data()是一个函数且可以保留数据类型。此外,还有点号(.)表示当前节点。

    使用要点

    XML例子: 
    <book><author>Tom John</author></book>

    用例举例
    text() book/author/text()
    string() book/author/string()
    data() book/author/data()
    . book/author/.

    特殊用例

    XML例子:

    <book>
        <author>Tom <em>John</em> cat</author>
        <pricing>
            <price>20</price>
            <discount>0.8</discount>
        </pricing>
    </book>

    text()

    经常在XPath表达式的最后看到text(),它仅仅返回所指元素的文本内容。

    let $x := book/author/text()
    return $x

    返回的结果是Tom cat,其中的John不属于author直接的节点内容。

    string()

    string()函数会得到所指元素的所有节点文本内容,这些文本讲会被拼接成一个字符串。

    let $x := book/author/string()
    return $x

    返回的内容是”Tom John cat”

    data()

    大多数时候,data()函数和string()函数通用,而且不建议经常使用data()函数,有数据表明,该函数会影响XPath的性能。

    let $x := book/pricing/string()
    return $x

    返回的是200.8

    let $x := book/pricing/data()
    return $x

    这样将返回分开的20和0.8,他们的类型并不是字符串而是xs:anyAtomicType,于是就可以使用数学函数做一定操作。

    let $x := book/pricing/price/data()
    let $y := book/pricing/discount/data()
    return $x*$y

    比如上面这个例子,就只能使用data(),不能使用text()或 string(),因为XPath不支持字符串做数学运算。

    总结

    text()不是函数,XML结构的细微变化,可能会使得结果与预期不符,应该尽量少用,data()作为特殊用途的函数,可能会出现性能问题,如无特殊需要尽量不用,string()函数可以满足大部分的需求。

  • 相关阅读:
    noip2007 tg day1t1 统计数字
    洛谷1123 取数游戏
    洛谷1123 取数游戏
    素数筛
    bzoj 1297 [SCOI2009]迷路
    bzoj 2115 [Wc2011] Xor——路径和环的转化
    poj 2154 Color——带优化的置换
    bzoj 1407 [Noi2002]Savage
    poj 1286 Necklace of Beads
    bzoj 4031 [HEOI2015]小Z的房间
  • 原文地址:https://www.cnblogs.com/P3nguin/p/7595877.html
Copyright © 2011-2022 走看看