Module: Sequel::Plugins::XmlSerializer

Defined in:
lib/sequel/plugins/xml_serializer.rb

Overview

The xml_serializer plugin handles serializing entire Sequel::Model objects to XML, and deserializing XML into a single Sequel::Model object or an array of Sequel::Model objects. It requires the nokogiri library.

Basic Example:

album = Album[1]
puts album.to_xml
# Output:
<?xml version="1.0"?>
<album>
  <id>1</id>
  <name>RF</name>
  <artist_id>2</artist_id>
</album>

You can provide options to control the XML output:

puts album.to_xml(:only=>:name)
puts album.to_xml(:except=>[:id, :artist_id])
# Output:
<?xml version="1.0"?>
<album>
  <name>RF</name>
</album>

album.to_xml(:include=>:artist)
# Output:
<?xml version="1.0"?>
<album>
  <id>1</id>
  <name>RF</name>
  <artist_id>2</artist_id>
  <artist>
    <id>2</id>
    <name>YJM</name>
  </artist>
</album>

You can use a hash value with :include to pass options to associations:

album.to_json(:include=>{:artist=>{:only=>:name}})
# Output:
<?xml version="1.0"?>
<album>
  <id>1</id>
  <name>RF</name>
  <artist_id>2</artist_id>
  <artist>
    <name>YJM</name>
  </artist>
</album>

In addition to creating XML, this plugin also enables Sequel::Model objects to be created by parsing XML:

xml = album.to_xml
album = Album.from_xml(xml)

In addition, you can update existing model objects directly from XML using from_xml:

album.from_xml(xml)

Additionally, to_xml also exists as a class and dataset method, both of which return all objects in the dataset:

Album.to_xml
Album.filter(:artist_id=>1).to_xml(:include=>:tags)

Such XML can be loaded back into an array of Sequel::Model objects using array_from_xml:

Album.array_from_xml(Album.to_xml) # same as Album.all

Usage:

# Add XML output capability to all model subclass instances (called before loading subclasses)
Sequel::Model.plugin :xml_serializer

# Add XML output capability to Album class instances
Album.plugin :xml_serializer

Defined Under Namespace

Modules: ClassMethods, DatasetMethods, InstanceMethods