2016-01-12 63 views
1

我是Xpath新手,在解決一個更復雜的問題之前,一直試圖使用xpath測試站點來介紹一些基本示例。通過Xpath導航XML

我想明白如何使用contains函數與其他條件(s),但努力了一點。

這裏是我的xml:

<root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org"> 
    <actors> 
     <actor id="1">Christian Bale</actor> 
     <actor id="2">Liam Neeson</actor> 
     <actor id="3">Michael Caine</actor> 
    </actors> 
    <foo:singers> 
     <foo:singer id="4">Tom Waits</foo:singer> 
     <foo:singer id="4">B.B. King</foo:singer> 
     <foo:singer id="6">Ray Charles</foo:singer> 
    </foo:singers> 
</root> 

要複製的XML類型(或HTML更精確),我試圖解析,我有重複了歌手的屬性之一。

所以我試圖使用包含找到foo:singer id = 4幷包含"Tom Waits"

從我已閱讀並例子我所看到的,你可以使用這種類型的表達式:

.//*[@id =4 and //foo:singer[contains(text(),'Tom Waits')]]/text() 

然而,這同時返回Tom WaitsBB King

如果我單獨使用這兩個表達式,他們會得到預期的結果,所以不確定它們是否能夠/如何組合。

非常感謝,如果你能幫助我。

Andrew

回答

1

一定要注意上下文。不需要嵌套謂詞。

.//*[@id =4 and contains(.,'Tom Waits')]/text() 

所以我試圖用包含查找富:歌手ID = 4,幷包含「湯姆等待」。

由於您將//foo:singer用於包含測試,因此整個文檔都處於上下文中,因此始終爲真。

0

使用

//foo:singer[contains(text(),'Tom Waits')]/text()