foo1

foo2foo4foo5

foo6to

ba...">

Nokogiri replace tag values

How to replace "foo" with "bar"?

FROM

<h1>foo1<p>foo2<a href="foo3.com">foo4</a>foo5</p>foo6</h1> 

to

 <h1>bar1<p>bar2<a href="foo3.com">bar4</a>bar5</p>bar6</h1> 

I only want to replace the internal content of the tag with no tag attributes.

Any ideas?

+2
source share
2 answers
 require 'rubygems' require 'nokogiri' doc = Nokogiri::HTML(DATA) doc.xpath('//text()').each {|foo| dummy = foo.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc)) dummy.add_previous_sibling(Nokogiri::XML::Text.new(foo.to_s.gsub(/foo/, "bar"), doc)) foo.remove dummy.remove } puts doc __END__ <h1>foo1<p>foo2<a href="foo3.com">foo4</a>foo5</p>foo6</h1> 

I would think that foo.inner_html.gsub!(/foo/, "bar") works, or maybe foo.inner_html = foo.inner_html.gsub(/foo/, "bar") , but it is not. The node dummy is to save the new node text according to the old node text.

+2
source

I could do

 nokogiri_doc.css('p').each { |p| p.inner_html = p.inner_html.gsub(/\n/, "<br/>") } 

To replace all shards \ n inside the p tag with br tags

+2
source

Source: https://habr.com/ru/post/896151/


All Articles