Logo

Programming-Idioms

  • Lisp
  • Go
  • JS
  • Pascal
  • D

Idiom #104 Save object into XML file

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

import orange.serialization._;
import orange.serialization.archives._;
import std.file;
auto archive = new XmlArchive!(char);
auto serializer = new Serializer(archive); 
serializer.serialize(x);
write("data.xml", archive.data);

Using the Orange serializer
import "encoding/xml"
import "os"
buffer, err := xml.MarshalIndent(x, "", "  ")
if err != nil {
	return err
}
err = os.WriteFile("data.xml", buffer, 0644)

xml.MarshalIndent is more human-readable than xml.Marshal.
require_once('XML/Serializer.php');
class Test
{
    public $f1;
    private $f2;

    public function __construct($f1, $f2)
    {
        $this->f1 = $f1;
        $this->f2 = $f2;
    }
}

$x = new Test('foo', 42);

$options = array(
  XML_SERIALIZER_OPTION_INDENT        => '    ',
  XML_SERIALIZER_OPTION_RETURN_RESULT => true
  );

$serializer = new XML_Serializer($options);
$result = "<?xml version=\"1.0\"?>\n" . $serializer->serialize($x);
file_put_contents('data.xml', $result);

Requires PEAR XML_Serializer
Note that private fields are not serialized.

New implementation...
< >
programming-idioms.org