module

XMLT::Serializable

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:

  • XMLT::Attributes: defines the attributes to be serialized with the property
  • XMLT::CData: sets the property to be (de)serialized as CData
  • XMLT::Field: sets general (de)serialization options
  • XMLT::Options: sets the XML document and indent options

Constructors

new(*, __xml_deserializable xml : XML::Node)
Source

Instance methods

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

TODO: pos args: version, encoding

Source
to_xml(*, builder : XML::Builder) : Nil
Source