1.XPath中的text()和string()區(qū)別
- 本質(zhì)區(qū)別
text()是一個node test,而string()是一個函數(shù),data()是一個函數(shù)且可以保留數(shù)據(jù)類型谈为。此外,還有點號(.)表示當(dāng)前節(jié)點。 - 使用要點
XML例子:
<book><author>Tom John</author></book>
image.png
XML例子:
1. <book>
2. <author>Tom <em>John</em> cat</author>
3. <pricing>
4. <price>20</price>
5. <discount>0.8</discount>
6. </pricing>
7. </book>
text()
經(jīng)常在XPath表達(dá)式的最后看到text()酥泞,它僅僅返回所指元素的文本內(nèi)容。
1. let $x := book/author/text()
2. return $x
返回的結(jié)果是Tom cat住册,其中的John不屬于author直接的節(jié)點內(nèi)容婶博。
string()
string()函數(shù)會得到所指元素的所有節(jié)點文本內(nèi)容,這些文本講會被拼接成一個字符串荧飞。
1. let $x := book/author/string()
2. return $x
返回的內(nèi)容是”Tom John cat”
data()
大多數(shù)時候凡人,data()函數(shù)和string()函數(shù)通用,而且不建議經(jīng)常使用data()函數(shù)叹阔,有數(shù)據(jù)表明挠轴,該函數(shù)會影響XPath的性能。
1. let $x := book/pricing/string()
2. return $x
返回的是200.8
1. let $x := book/pricing/data()
2. return $x
這樣將返回分開的20和0.8耳幢,他們的類型并不是字符串而是xs:anyAtomicType岸晦,于是就可以使用數(shù)學(xué)函數(shù)做一定操作欧啤。
1. let $x := book/pricing/price/data()
2. let $y := book/pricing/discount/data()
3. return $x*$y
比如上面這個例子,就只能使用data()启上,不能使用text()或 string()邢隧,因為XPath不支持字符串做數(shù)學(xué)運算。
總結(jié)
text()不是函數(shù)冈在,XML結(jié)構(gòu)的細(xì)微變化倒慧,可能會使得結(jié)果與預(yù)期不符,應(yīng)該盡量少用包券,data()作為特殊用途的函數(shù)纫谅,可能會出現(xiàn)性能問題,如無特殊需要盡量不用溅固,string()函數(shù)可以滿足大部分的需求付秕。
2.Xpath 常用函數(shù)
- contains (): //div[contains(@id,'in')] ,表示選擇id中包含有’in’的div節(jié)點
- text():由于一個節(jié)點的文本值不屬于屬性,比如“<a class=”baidu“ href=”http://www.baidu.com“>baidu</a>”,所以侍郭,用text()函數(shù)來匹配節(jié)點://a[text()='baidu']
- last():前面已介紹
- starts-with(): //div[starts-with(@id,'in')] 询吴,表示選擇以’in’開頭的id屬性的div節(jié)點
- not()函數(shù),表示否定励幼,//input[@name=‘identity’ and not(contains(@class,‘a(chǎn)’))] 汰寓,表示匹配出name為identity并且class的值中不包含a的input節(jié)點。 not()函數(shù)通常與返回值為true or false的函數(shù)組合起來用苹粟,比如contains(),starts-with()等有滑,但有一種特別情況請注意一下:我們要匹配出input節(jié)點含有id屬性的,寫法如下://input[@id]嵌削,如果我們要匹配出input節(jié)點不含用id屬性的毛好,則為://input[not(@id)]