开发者

how to find all the child nodes inside the matched elements (including text nodes)?

开发者 https://www.devze.com 2022-12-08 10:07 出处:网络
in jquery its quite simple for instance $(\"br\").parent().contents().each(function() { but for nokogiri, xpath,

in jquery its quite simple

for instance

$("br").parent().contents().each(function() {

but for nokogiri, xpath,

its not w开发者_如何学Corking out quite well

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


require 'rubygems'
require 'nokogiri'

doc = Nokogiri::HTML(DATA.read)
fruits = doc.xpath('//br/../text()').map { |text| text.content.strip }
p fruits


__END__
<html>
<body>
  <div>
    apple<br>
    banana<br>
    cherry<br>
    orange<br>
  </div>
</body> 


I'm not familiar with nokogiri, but are you trying to find all the children of any element that contains a <br/>? If so, then try:

//*[br]/node()

In any case, using text() will only match text nodes, and not any sibling elements, which may or may not be what you want. If you actually only want text nodes, then

//*[br]/text()

should do the trick.

0

精彩评论

暂无评论...
验证码 换一张
取 消