views:

1117

answers:

3

I like to do my server side programming in C, but need to inter-operate with some XML.

What I need to write is some function that, given a C structure, or nested structure, and another structure (or nested structures) that describes the elements in the C structure, spits it out as XML. And another function that reads the XML, verifies that it matches the description of the C structures, and populates the C structures.

I'm quite certain this has been done many times before, but there is so much other info about XML out there that I'm not having any luck composing a Google query that doesn't return a lot of unrelated stuff.

I'm not looking for a library - just a few hundred lines of C code to parse the XML.

A: 

One way you could do it if you don't find any premade libraries or code is to write a toXML() function like the usual toString() functions. Then a toStruct(char*) that deserializes the XML back into the struct

ThePosey
Yes, something like that. And that's what I'm hoping to avoid having to write if there is code out there that does that.
Matthias Wandel
+1  A: 

You aren't going to be able to parse XML in the general case in only a few hundred lines of code. There are several XML parser libraries out there, of which expat comes to mind. Expat was written in C, and has a C-friendly API.

Serialization is likely to be easier, assuming you don't go nuts with the data types you support.

Either way, where this is going to cause you headaches is in the maintenance of the correspondence between struct layout and XML schema.

You might want to look into libraries like SCEW that aim to conceal the event-driven nature of expat's implementation and present something more like a DOM tree. There are also various libraries that implement SOAP on top of expat, and those necessarily need to handle marshaling of data in and out of XML packets.

RBerteig
Well, parsing the XML is the easy part (and there are many libraries that are easier than expat such as libxml). THe hard part is the two-way mapping/conversion between C structs and XML.
bortzmeyer
Good serialization is always harder than it looks, no matter what the underlying protocol is. IMHO, XML makes good serialization even harder to do well, but that is just from my personal experience. Your mileage will vary, probably considerably.
RBerteig
A: 

I guess there isn't really something readily available that I can use, so I wrote a simple XML parser in C.
Its only good enough for my need, but its also only 350 lines of C code.

Matthias Wandel
Writing a XML parser in C??? Very strange idea. There are already several very good ones. See http://stackoverflow.com/questions/399704/xml-parser-for-c
bortzmeyer
I wasn't prepared to include a lot of dependencies and libraries that would more than double the size of my project.
Matthias Wandel