Logo

Programming-Idioms

History of Idiom 104 > diff from v19 to v20

Edit summary for version 20 by programming-idioms.org:
[Ruby] +DemoURL

Version 19

2022-04-19, 15:00:22

Version 20

2022-04-20, 08:57:11

Idiom #104 Save object into XML file

Write the contents of the object x into the file data.xml.

Idiom #104 Save object into XML file

Write the contents of the object x into the file data.xml.

Variables
x,data,xml
Variables
x,data,xml
Imports
# gem install xml-mapping
require 'xml/mapping'
Imports
# gem install xml-mapping
require 'xml/mapping'
Code
class Person
  include XML::Mapping
  attr_accessor :name, :surname, :age, :children

  text_node :from, "@from"
  text_node :name, "Name"
  text_node :surname, "Surname"

  def initialize(name, surname, ..)
    # ...
  end
end

x = Person.new(..)
x.save_to_xml.write($stdout,2) # nicely prints
x.save_to_file('data.xml')
Code
class Person
  include XML::Mapping
  attr_accessor :name, :surname, :age, :children

  text_node :from, "@from"
  text_node :name, "Name"
  text_node :surname, "Surname"

  def initialize(name, surname, ..)
    # ...
  end
end

x = Person.new(..)
x.save_to_xml.write($stdout,2) # nicely prints
x.save_to_file('data.xml')
Comments bubble
need to create the schema in the class.
Comments bubble
need to create the schema in the class.
Doc URL
https://stackoverflow.com/questions/58662688/xml-serialization-from-class-instance-in-ruby-with-custom-attributes
Doc URL
https://stackoverflow.com/questions/58662688/xml-serialization-from-class-instance-in-ruby-with-custom-attributes
Origin
https://multi-io.github.io/xml-mapping/#label-Example
Origin
https://multi-io.github.io/xml-mapping/#label-Example
Demo URL
https://replit.com/@RiccardoCarless/Write-XML-to-file#main.rb