Skip to content

Instantly share code, notes, and snippets.

@flavorjones
Created November 5, 2020 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flavorjones/7d0e5e489acc80801b8de57fd030ab1f to your computer and use it in GitHub Desktop.
Save flavorjones/7d0e5e489acc80801b8de57fd030ab1f to your computer and use it in GitHub Desktop.
Nokogiri::XML::Node serialization
#! /usr/bin/env ruby
# related to https://groups.google.com/g/nokogiri-talk/c/XoKIzgbcBpU/m/9o3tbD6WCQAJ
require "nokogiri"
html = <<~EOF
<html>
<body>
<div>123 Fake St.<br>City, State&nbsp;65432</div>
</body>
</html>
EOF
doc = Nokogiri::HTML(html)
address = doc.at_css("div")
address # => #<Nokogiri::XML::Element:0x78 name="div" children=[#<Nokogiri::XML::Text:0x3c "123 Fake St.">, #<Nokogiri::XML::Element:0x50 name="br">, #<Nokogiri::XML::Text:0x64 "City, State 65432">]>
address.inspect # => "#<Nokogiri::XML::Element:0x78 name=\"div\" children=[#<Nokogiri::XML::Text:0x3c \"123 Fake St.\">, #<Nokogiri::XML::Element:0x50 name=\"br\">, #<Nokogiri::XML::Text:0x64 \"City, State 65432\">]>"
address.content # => "123 Fake St.City, State 65432"
address.text # => "123 Fake St.City, State 65432"
address.inner_text # => "123 Fake St.City, State 65432"
address.to_s # => "<div>123 Fake St.<br>City, State 65432</div>"
address.to_html # => "<div>123 Fake St.<br>City, State 65432</div>"
address.to_xml # => "<div>123 Fake St.<br/>City, State 65432</div>"
address.to_xhtml # => "<div>123 Fake St.<br />City, State 65432</div>"
address.inner_html # => "123 Fake St.<br>City, State 65432"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment