dimanche 28 octobre 2007

Mlxsd : First Generation

Eh oui, la première génération complète de ma spécification XSD restreinte a vu le jour! Voilà un exemple simple de xsd, et du code ocaml généré (bon, d'accord, j'avoue, j'ai indenté à la main le code généré pour faciliter la lisibilité, mais bon, ça ne va pas changer à la compilation!):

simple.xsd


<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:complexType name="v_t">
<xs:sequence>
<xs:element name="x" type="xs:integer"/>
<xs:element name="y" type="xs:integer"/>
<xs:element name="z" type="xs:integer"/>
</xs:sequence>
</xs:complexType>

<xs:element name="v" type="v_t"/>

</xs:schema>


simple.ml

module V_t =
struct

type t =
{
x: int;
y: int;
z: int
}

let from_xml xml =
match xml with
[Xml.Element ("x", [], [Xml.PCData x]);
Xml.Element ("y", [], [Xml.PCData y]);
Xml.Element ("z", [], [Xml.PCData z])] ->
{x = int_of_string x;
y = int_of_string y;
z = int_of_string z}
| _ -> raise Not_found

let to_xml t =
[Xml.Element ("x", [], [Xml.PCData (string_of_int t.x)]);
Xml.Element ("y", [], [Xml.PCData (string_of_int t.y)]);
Xml.Element ("z", [], [Xml.PCData (string_of_int t.z)])]

end


type v = { v : V_t.t }

let v_from_xml xml =
match xml with
Xml.Element ("v", [], v) -> { v = V_t.from_xml v }
| _ -> raise Not_found

let v_to_xml t =
Xml.Element ("v", [], V_t.to_xml t.v)


Tout cela suivi bien entendu du petit exemple d'utilisation:


# #load "xml-light.cma";;
# #load "simple.cmo";;

# Simple.v_to_xml;;
- : Simple.v -> Xml.xml = <fun>
# Simple.v_from_xml;;
- : Xml.xml -> Simple.v = <fun>

# let input = "<v><x>9</x><y>8</y><z>7</z></v>";;
val input : string = "<v><x>9</x><y>8</y><z>7</z></v>"

# let xml = Xml.parse_string input;;
val xml : Xml.xml =
Xml.Element
("v", [],
[Xml.Element ("x", [], [Xml.PCData "9"]);
Xml.Element ("y", [], [Xml.PCData "8"]);
Xml.Element ("z", [], [Xml.PCData "7"])])

# let s = Simple.v_from_xml xml;;
val s : Simple.v =
{Simple.v = {Simple.V_t.x = 9; Simple.V_t.y = 8; Simple.V_t.z = 7}}

# Simple.v_to_xml s;;
- : Xml.xml =
Xml.Element
("v", [],
[Xml.Element ("x", [], [Xml.PCData "9"]);
Xml.Element ("y", [], [Xml.PCData "8"]);
Xml.Element ("z", [], [Xml.PCData "7"])])

# Xml.to_string (Simple.v_to_xml s);;
- : string = "<v><x>9</x><y>8</y><z>7</z></v>"


C'est maintenant que les difficultés vont commencer: le support des choix, et des cardinaux!

Aucun commentaire: