Error:

Parse XML string

# gem install nokogiri
require 'nokogiri'
xml = '<category name="cat5"> <article>http://quackquack42.com/art9238.xml</article> </category>'
doc = Nokogiri.XML(xml)
cat_name = doc.root.attr("name") # => "cat5"

Parse XML file

# gem install nokogiri
require 'nokogiri'
f = File.open('data.xml', 'rb')
doc = Nokogiri::XML(f)
cat_name = doc.root.attr("name")

Iterate over DOM structure

# gem install nokogiri
require 'nokogiri'
xml = <<__EOXML__
<category name="cat5">
  <article>http://quackquack42.com/art9238.xml</article>
   <article>http://quackquack42.com/art0239.xml</article>
</category>
__EOXML__
doc = Nokogiri.XML(xml)
doc.root.children().each do |child|
  # skip non-element
  next unless child.element?
  url = child.content
end

Access XML data using XPath

# gem install nokogiri
require 'nokogiri'
xml = <<__EOXML__
<category name="cat5">
  <article>http://quackquack42.com/art9238.xml</article>
   <article>http://quackquack42.com/art0239.xml</article>
</category>
__EOXML__
doc = Nokogiri.XML(xml)
cat_name = doc.xpath("./category/@name").text # => "cat5"
doc.xpath("./category/article").each do |n|
  url = n.text
  # handle URL
end

Generate XML

# gem install nokogiri
require 'nokogiri'
articles = ['http://quackquack42.com/art9238.xml', 'http://quackquack42.com/art0239.xml']

builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
  xml.category(:name => 'cat5') {
    articles.each do |a|
        xml.article a
    end
  }
}
end

puts builder.to_xml

Parse JSON string

# gem install json
require 'json'
json_data = '{"author":{"first_name":"Alex","last_name":"T."},"title": "Some things..."}'
obj = JSON.parse(json_data)
# => {"author"=>{"first_name"=>"Alex", "last_name"=>"T."}, "title"=>"Some things..."}

Serialize data to JSON

require 'json'

data = {:author => "John Doe"}
s = JSON.generate(data) # => "{\"author\":\"John Doe\"}"

Parse CSV file

require 'csv'
# Line by line
CSV.foreach("test.csv") do |row|
    puts "--> #{row}"
end

# All at once
data = CSV.read("test.csv")

Parse CSV string

require 'csv'
csv_data = "1,2,3\na,b,c"
CSV.parse(csv_data) do |row|
    puts "--> #{row}"
end

Generate CSV file

require 'csv'
CSV.open("test.csv", "wb") do |csv|
  csv << [1, 2, 3]
  csv << ['a', 'b', 'c']
end

Generate CSV string

require 'csv'
s = CSV.generate do |csv|
  csv << [1, 2, 3]
  csv << ['a', 'b', 'c']
end

# => "1,2,3\na,b,c\n"

Parse YAML file

require 'yaml'
data = YAML.load_file('test.yml')