1

I searched SO and found a reference Accepted Answer but it did not solve my issue. I have a simple html dom which is:

<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>

I am trying to use xPath to get all (a joined string) "head-name" and the "sub-name" class' content. My xPath expression did not succeed:

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

the error message I am getting, while trying it in Chrome's console, is:

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.(…)

If there is another expression I could use (like following sibling), would be nice.

thanks a lot

Community
  • 1
  • 1
DingDong
  • 75
  • 1
  • 14

1 Answers1

0

Here is answer in XPath 2.0 (string-join() is XPath 2.0 function)

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

It's not possible to do asked string joining via pure XPath 1.0 - you just can list all nodes without joining (and then iterate and join via external code e.g. JavaScript), may be it'll applicable for you.

//div[@class='name-hg']//text()
CroWell
  • 606
  • 8
  • 15
  • I see - you're trying to run it in Chrome console, just checked that - Chrome console supports only XPath 1.0 - therefore you can't use function **string-join** here. And there aren't any way to convert sequence of string to one string via pure XPath 1.0. Updating original answer with this details – CroWell Sep 23 '15 at 11:20
  • Oh, much appreciated! I will look into xPath v2 then. – DingDong Sep 26 '15 at 08:57