tags:

views:

463

answers:

3
</div>
apple
<br>
banana
<br/>
watermelon
<br>
orange

Assuming the above, how is it possible to use Xpath to grab each fruit ? Must use xpath of some sort.

should i use substring-after(following-sibling...) ?

EDIT: I am using Nokogiri parser.

+3  A: 

Well, you could use "//br/text()", but that will return all the text-nodes inside the <br> tags. But since the above isn't well-formed xml I'm not sure how you are going to use xpath on it. Regex is usually a poor choice for html, but there are html (not xhtml) parsers available. I hesitate to suggest one for ruby simply because that isn't "my area" and I'd just be googling...

Marc Gravell
i am using nokogiri.
+1  A: 

There are several issues here:

  1. XPath works on XML - you have HTML which is not XML (basically, the tags don't match so an XML parser will throw an exception when you give it that text)

  2. XPath normally also works by finding the attributes inside tags. Seeing as your <br> tags don't actually contain the text, they're just in-between it, this will also prove difficult

Because of this, what you probably want to do is use XPath (or similar) to get the contents of the div, and then split the string based on <br> occurrences.

As you've tagged this question with ruby, I'd suggest looking into hpricot, as it's a really nice and fast HTML (and XML) parsing library, which should be much more useful than mucking around with XPath

Orion Edwards
yes. i am using Nokogiri html parsing library. i guess exploding is the best working solution here.
+1  A: 

Try the following, which gets all text siblings of <br> tags as array of strings stripped from trailing and leading whitespaces:

require 'rubygems'
reguire 'nokogiri'

doc = Nokogiri::HTML(DATA)

fruits =
  doc.xpath('//br/following-sibling::text()
           | //br/preceding-sibling::text()').map do |fruit| fruit.to_s.strip end

puts fruits

__END__
</div>
apple
<br>
banana
<br/>
watermelon
<br>
orange

Is this what you want?

andre-r