Xml in Ruby

Here’s the translation of the XML example from Go to Ruby, formatted in Markdown suitable for Hugo:

require 'nokogiri'

# Plant will be mapped to XML. We use Nokogiri for XML processing in Ruby.
# The structure is defined using a class with instance variables.
class Plant
  attr_accessor :id, :name, :origin

  def initialize(id, name, origin = [])
    @id = id
    @name = name
    @origin = origin
  end

  def to_s
    "Plant id=#{@id}, name=#{@name}, origin=#{@origin}"
  end
end

# Main execution
coffee = Plant.new(27, "Coffee", ["Ethiopia", "Brazil"])

# Create XML representing our plant
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
  xml.plant(id: coffee.id) {
    xml.name coffee.name
    coffee.origin.each do |origin|
      xml.origin origin
    end
  }
end

# Print the XML
puts builder.to_xml

# To add a generic XML header to the output, it's already included by Nokogiri

# Parse XML back into a Plant object
parsed_xml = Nokogiri::XML(builder.to_xml)
p = Plant.new(
  parsed_xml.at_xpath('/plant/@id').value.to_i,
  parsed_xml.at_xpath('/plant/name').content,
  parsed_xml.xpath('/plant/origin').map(&:content)
)
puts p

# Create another plant
tomato = Plant.new(81, "Tomato", ["Mexico", "California"])

# The nested XML structure
class Nesting
  attr_accessor :plants

  def initialize(plants = [])
    @plants = plants
  end
end

nesting = Nesting.new([coffee, tomato])

# Create nested XML
nested_builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
  xml.nesting {
    xml.parent {
      xml.child {
        nesting.plants.each do |plant|
          xml.plant(id: plant.id) {
            xml.name plant.name
            plant.origin.each do |origin|
              xml.origin origin
            end
          }
        end
      }
    }
  }
end

puts nested_builder.to_xml

This Ruby code demonstrates XML processing using the Nokogiri gem, which is a popular choice for handling XML in Ruby. Here’s a breakdown of the translation:

  1. We define a Plant class to represent the structure of our data.

  2. Instead of using struct tags for XML mapping, we use Nokogiri to build and parse XML.

  3. The MarshalIndent function is replaced with Nokogiri’s XML builder, which allows us to create formatted XML.

  4. XML parsing is done using Nokogiri’s parsing methods and XPath queries.

  5. The nested XML structure is created using a similar approach with the Nokogiri builder.

To run this code, you would need to install the Nokogiri gem (gem install nokogiri) and then execute the script with Ruby.

The output would be similar to the original, showing the XML representations of the plants and the nested structure.

This example demonstrates how to create, parse, and manipulate XML in Ruby, which is conceptually similar to the original example but uses Ruby-specific tools and idioms.