module XMLT::Serializable

Overview

The XMLT::Serializable module generates methods for serializing and deserializing classes or structs when included.

Example

require "xmlt"

class Location
  include XMLT::Serializable

  @[XMLT::Field(key: "lat")]
  property latitude : Float64
  @[XMLT::Field(key: "long")]
  property longitude : Float64
end

class House
  include XMLT::Serializable

  property address : String
  @[XMLT::Field(omit_nil: true)]
  property location : Location?
end

xml = <<-XML
  <Place>
    <address>Crystal Palace</address>
    <location>
      <long>51.4221</long>
      <lat>0.0709</lat>
    </location>
  </Place>
XML

place = Place.from_xml xml, root: "Place"
pp place # =>
# Place(
#   @address="Crystal Palace",
#   @location=Location(
#     @latitude=0.0709,
#     @longitude=51.4221
#   )
# )

puts place.to_xml # =>
# <Place>
#   <address>Crystal Palace</address>
#   <location>
#     <long>51.4221</long>
#     <lat>0.0709</lat>
#   </location>
# </Place>

Usage

Including XMLT::Serializable will create #to_xml methods for all methods on the class or struct. These methods serialize serialize their value to an XML format with the key being the name of the property unless overriden. Nil values will serialize to a self-closing element unless omitted, whereas empty values (e.g. empty strings) will serialize to a normal empty element.

Annotations

How properties are serialized and deserialized can be modified using annotations:

Defined in:

serializable.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(*, __xml_deserializable xml : XML::Node) #

[View source]

Instance Method Detail

def to_xml(*, indent : IndentOptions = nil) : String #

TODO pos args: version, encoding


[View source]
def to_xml(*, builder : XML::Builder) : Nil #

[View source]