Is there an easy way to go from an Ocaml data type to a corresponding xml representation?
Suppose that I have the following types:
type A =
| FirstA of B list
| SecondA of C * string
type B = B1 | B2
type C = {
my_field: int;
}
For the value SecondA (C {my_field=10}, "just a value")
I would like to get maybe something like this:
<A constructor="FirstA">
<C><my_field>10</my_field></C>
<string>just a value</string>
</A>
Is there any library that can do something like this? Or, if I have to do it myself what would be the best approach? Note that I want to apply this to multiple different data types.
I am aware of data-type generic programing techniques but they are too "heavy" to use in my case.
If I understood your question correctly, there's IoXML that can do it:
IoXML is a Camlp5 syntax extension for OCaml mli and ml files which generates XML parsers and printers for all types you define.
There's a similar one for JSON: https://github.com/mirage/shelf
If you're fine with using JSON, I'd suggest also looking at ATD/yojson. This system relies on external data definition language, but it still produces idiomatic OCaml type definitions.
UPDATE (08/15/2011): Now my own Piqi project can do this as well. It can serialize OCaml data using 4 different formats: Google Protocol Buffers, JSON, XML and Piq.
I'm not sure what you mean by "data-type generic programming techniques". There are multiple libraries which use the camlp4 preprocessor to automatically derive serializers from type declarations:
Although none of these produces XML, they might be of some help. Especially s-expressions generated by sexplib are not too dissimilar to XML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With