A simple C to XML serializer

By | March 26, 2011

Some days ago I was asked for writing a program that could read any given C struct or union from a header file and serialize it to XML.

I decided to write a program, called SC2XML: Simple C to XML serializer, flexible enough for adding later new C constructs like enums and typedefs.

In order to serialize any valid C struct/union I needed a C grammar and something that could scan and parse the file following that grammar. The best tools for doing this are lex and yacc. In Linux, Flex and Bison are the Open Source implementations of these old but quite useful Unix tools.
I strongly recommend these tools if you need to create a compiler, an interpreter or even a shell (you can have a look at a project called tarasca that I wrote some years ago as a proof of concept of a Cisco-like shell).

Since writing an ANSI C grammar is not a easy task, I downloaded the lex and yacc implementations of the ANSI C grammar written by Jutta Degener and modified it because it misses a few things like user-defined data types.

The first version of this program could potentially serialize other C constructs and almost any C code since it uses an almost full-compatible C grammar (see the header comment of scanner.l and parser.y for details).

The sc2xml package needs, as requirements, the following two standard libraries:

  • glib-2
  • libxml2

The package already provides the files generated by Flex and Bison called lex.yy.c, parser.c and parser.tab.h. These files are created from scanner.l and parser.y. Thus, if you modified the last two files, you will also need Flex and Bison.

You can configure, compile and install sc2xml using the traditional way:

./configure
make
sudo make install

This version, as it is normal with a first alpha release, has some limitations and bugs. At them moment, it doesn’t support some constructs like

  • Anonymous structs/unions
  • Multi-line pre-processor directives and macros

You can have a look at the README for more details about the current limitations and bugs.

If I have the time or there is the interest for expanding this program, I would post it in sourceforge or gitorious. Meanwhile, you can download the source code from here: sc2xml-0.0.1.tar.gz

Leave a Reply

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