开发者

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

开发者 https://www.devze.com 2023-02-17 18:00 出处:网络
Is there an easy way to go from an Ocaml data type to a corresponding xml representation? Suppose that I have the following types:

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 progra开发者_Go百科ming 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:

  • 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消