HowTo: GObject Serialization to XML using GXml

While GXml has C API, it is written in Vala, then this posts will show you how to use GXml’s Vala API to get GObject to XML and back easy.

Lets start with a simple class and GXml’s implementation of GXml.Serializable, called GXml.SerializableObjectModel:

using GXml;

public class Record : GXml.SerializableObjectModel {
  public string name { get; set; }

  // GXml.SerializableObjectModel overrides
  public override string node_name () { return "Record"; }
  public override string to_string () { return @"Record: $name"; }

The above example, defines a class called Record witch should be written in XML as:

<Record name="Daniel"/>

This just happen if is set, if no you’ll get:


In order to get this XML to be written you’ll need:

var r = new Record (); = "Daniel";
var d = new GDocument ();
r.serialize (d);
stdout.printf (@"$d");

The above code will print an XML representation of your object, with the given values, as shown above.

If you have an XML file or string, you can use following to read data from:

var r = new Record ();
var d = new GDocument.from_string ("<Record name=\"Jhon\"/>");
r.deserialize (d);
stdout.printf (@"$r");

The above code will print your object string representation using Record.to_string().

GXml.SerializableObjectModel will inspect all your public properties, trying to print out string representation of each. Most basic types are sopported, while you can override default GXml.SerializableObjectModel.serialize_property() in order to catch up when an special property like GLib.List is corrently serialize to create your custom serialization; if you do so, remember to override GXml.SerializableObjectModel.deserialize_property() to get back string to your property. Remember, GXml.SerializableObjectModel is just an implementation of GXml.Serializable interface and you can both, override default methods or implement your own.

Next time we can review how a set of XML tags could be de/serialized from XML using builtin GXml serializable collections.

Author: despinosa

Linux and GNOME user, full time, since 2001. Actual maintainer of GXml and contributor to other projects mainly on GObject Introspection support.

Leave a Reply

Your email address will not be published. Required fields are marked *