Reputation: 146
I am using Nokogiri with Ruby on Rails v2.3.8.
Is there a way in which I can avoid pretty-printing in Nokogiri while using to_html
?
I read that to_xml
allows this to be done using to_xml(:indent => 0)
, but this doesn't work with to_html
.
Right now I am using gsub
to strip away new-line characters. Does Nokogiri provide any option to do it?
Upvotes: 8
Views: 2002
Reputation: 787
I solved this using .to_html(save_with: 0)
?
2.1.0 :001 > require 'nokogiri'
=> true
2.1.0 :002 > doc = Nokogiri::HTML.fragment('<ul><li><span>hello</span> boom!</li></ul>')
=> #<Nokogiri::HTML::DocumentFragment:0x4e4cbd2 name="#document-fragment" children=[#<Nokogiri::XML::Element:0x4e4c97a name="ul" children=[#<Nokogiri::XML::Element:0x4e4c47a name="li" children=[#<Nokogiri::XML::Element:0x4e4c240 name="span" children=[#<Nokogiri::XML::Text:0x4e4c0a6 "hello">]>, #<Nokogiri::XML::Text:0x4e4c86c " boom!">]>]>]>
2.1.0 :003 > doc.to_html
=> "<ul><li>\n<span>hello</span> boom!</li></ul>"
2.1.0 :004 > doc.to_html(save_with: 0)
=> "<ul><li><span>hello</span> boom!</li></ul>"
tested on: nokogiri (1.6.5) + libxml2 2.7.6.dfsg-1ubuntu1 + ruby 2.1.0p0 (2013-12-25 revision 44422) [i686-linux]
Upvotes: 7
Reputation: 1023
You can use Nokogiri::HTML.fragment()
instead of just Nokogiri::HTML()
. When you perform to_html
it won't add newlines, a DOCTYPE header or make it 'pretty' in any way.
Upvotes: 3