ruby - Nokogiri: need to turn markup partitioned by `hr` into divs -


given markup inside html document looks this

<h3>test</h3> <p>test</p> <hr/> <h3>test2</h3> <p>test2</p> <hr/> 

i'd to produce this

<div>   <h3>test</h3>   <p>test</p> </div> <div>   <h3>test2</h3>   <p>test2</p> </div> 

what's elegant way with nokogiri?

edit: reworked answer bit cleaner.
edit2: small rewrite shorten 2 lines

require 'nokogiri'     doc = nokogiri::html <<endhtml   <h3>test</h3>   <p>test</p>   <hr/>   <h3>test2</h3>   <p>test2</p>   <hr/> endhtml  body = doc.at_css('body')         # created parsing html kids = body.xpath('./*')          # every child of body body.inner_html = ""              # empty body have our nodes  div = (body << "<div>").first     # create our first container in body kids.each |node|               # every child in body...   if node.name=='hr'                   div = (body << '<div>').first # create new container stuff   else                                 div << node                   # move last container   end                              end                                div.remove unless div.child       # rid of trailing, empty div  puts body.inner_html #=> <div> #=> <h3>test</h3> #=> <p>test</p> #=> </div> #=> <div> #=> <h3>test2</h3> #=> <p>test2</p> #=> </div> 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -