2015-09-21 38 views
1

我搜索到了,找到了一個參考Accepted Answer,但它沒有解決我的問題。我有一個簡單的HTML DOM是:xpath - 加入/ concat子節點兄弟文本

<div class="name-hg"> 
    <h2 class="head-name"><a href="http://www.example.com/example.html" title="Example title">Times have changed</a></h2> 
    <div class="sub-name">10 Things you did not know about time</div> 
</div> 
<div class="name-hg"> 
    <h2 class="head-name"><a href="http://www.example.com/example.html" title="Example title">A Guide to mental fitness</a></h2> 
    <div class="sub-name">I am fit... mentally that is.</div> 
</div> 
<div class="name-hg"> 
    <h2 class="head-name"><a href="http://www.example.com/example.html" title="Example title">Sllippers &amp; Boots</a></h2> 
    <div class="sub-name">Fashion for the eccentric</div> 
</div> 
<div class="name-hg"> 
    <h2 class="head-name"><a href="http://www.example.com/example.html" title="Example title">Bic Pen Era</a></h2> 
    <div class="sub-name">Your childhood could not have been better</div> 
</div> 

我試圖使用XPath來獲取所有(的接字符串)「頭名」和「副名」類的內容。我的XPath表達式沒有成功:

$x("string-join((//div[@class='name-hg']/h2[@class='head-name']/a/text(), //div[@class='name-hg']/div[@class='sub-name']/text()),' ')") 

錯誤消息我得到,而在Chrome的控制檯嘗試它,就是:

Uncaught DOMException: Failed to execute 'evaluate' on 'Document': The string 'string-join((//div[@class='name-hg']/h2[@class='head-name']/a/text(), //div[@class='name-hg']/div[@class='sub-name']/text()),' ')' is not a valid XPath expression.(…) 

如果有另一種表達,我可以使用(如下面的兄弟姐妹) , 會好的。

非常感謝

回答

0

這是答案的XPath 2.0(字符串連接()是的XPath 2.0功能)

normalize-space(string-join(//div[@class='name-hg']//text(), ' ')) 

這是不可能做到問字符串連接通過純粹的XPath 1.0 - 你只可以在不加入的情況下列出所有節點(然後通過外部代碼(例如JavaScript)進行迭代和連接),可能適用於您。

//div[@class='name-hg']//text() 
+0

謝謝。我試過了,但沒有成功。 – DingDong

+0

我看到了 - 您正嘗試在Chrome控制檯中運行它,只是檢查了一下 - Chrome控制檯僅支持XPath 1.0 - 因此您無法在此處使用函數** string-join **。並且沒有任何方法可以通過純XPath 1.0將字符串序列轉換爲一個字符串。用這個細節更新原始答案 – CroWell

+0

哦,非常感謝!然後我會研究xPath v2。 – DingDong

相關問題