More documentation here: http://library.gnome.org/devel/glib/stable/glib-Simple-XML-Subset-Parser.html
This example uses a class and ignores comments and errors.
class TestParser: Object {
const MarkupParser parser = { // It's a structure, not an object
start,// when an element opens
end, // when an element closes
text, // when text is found
null, // when comments are found
null // when errors occur
};
MarkupParseContext context;
int depth = 0; // used to indent the output
construct {
context = new MarkupParseContext(
parser, // the structure with the callbacks
0, // MarkupParseFlags
this, // extra argument for the callbacks, methods in this case
destroy // when the parsing ends
);
}
void print_indent () {
for (var i=0; i < depth; i++)
print ("\t");
}
void destroy() {
print ("Releasing any allocated resource\n");
}
public bool parse(string content) throws MarkupError {
return context.parse(
content,
-1); // content size or -1 if it's zero-terminated
}
void start (MarkupParseContext context, string name,
string[] attr_names, string[] attr_values) throws MarkupError {
print_indent ();
print ("begin %s {", name);
for (int i = 0; i < attr_names.length; i++)
print ("%s: %s", attr_names[i], attr_values[i]);
print ("}\n");
depth ++;
}
void end (MarkupParseContext context, string name) throws MarkupError {
depth --;
print_indent ();
print ("end %s\n", name);
}
void text (MarkupParseContext context,
string text, size_t text_len) throws MarkupError {
print_indent ();
print ("text '%s'\n", text);
}
}
void main()
{
TestParser parser = new TestParser ();
string data = "<elm1 attrib ='hello'><elm2/><elm3>muhehehe</elm3></elm1>";
try {
parser.parse (data);
}
catch (Error e) {
print ("%s\n", e.message);
}
}