Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Ocaml datatype to xml and the other way around?

Tags:

xml

ocaml

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.

like image 917
Calin Avatar asked Mar 16 '11 15:03

Calin


2 Answers

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.

like image 95
alavrik Avatar answered Oct 31 '22 12:10

alavrik


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:

  • sexplib by Jane St. Capital (http://ocaml.janestcapital.com/?q=node/13)
  • deriving by Jeremy Yallop (http://portal.acm.org/citation.cfm?id=1292548) and https://github.com/jaked/deriving

Although none of these produces XML, they might be of some help. Especially s-expressions generated by sexplib are not too dissimilar to XML.

like image 24
ulricha Avatar answered Oct 31 '22 12:10

ulricha