Minimal dependency-free XML parser and serializer
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

OCaml 98.1%
Dune 0.5%
Other 1.4%
24 1 0

Clone this repository

https://tangled.org/gazagnaire.org/ocaml-xmlt https://tangled.org/did:plc:jhift2vwcxhou52p3sewcrpx/ocaml-xmlt
git@git.recoil.org:gazagnaire.org/ocaml-xmlt git@git.recoil.org:did:plc:jhift2vwcxhou52p3sewcrpx/ocaml-xmlt

For self-hosted knots, clone URLs may differ based on your setup.

Download tar.gz
README.md

xmlt#

Declarative XML codecs using GADT-based bidirectional maps and bytesrw streaming.

Overview#

Xmlt provides type-safe XML encoding and decoding using a combinator-based approach inspired by the {e finally tagged} pattern from An alphabet for your data soups by Daniel Buenzli. Define a codec once and use it for both encoding and decoding.

Codecs compose from attributes, child elements, and text content using the El builder module, the same way Jsont composes JSON objects from members. Streaming I/O is built on bytesrw.

Installation#

opam install xmlt

Usage#

open Xmlt

(* Define a codec for a record type *)
type person = { name : string; age : int; email : string option }

let person =
  El.(element "person"
    (obj (fun name age email -> { name; age; email })
     |> attr "name" Attr.string ~enc:(fun p -> p.name)
     |> attr "age" Attr.int ~enc:(fun p -> p.age)
     |> child_opt "email" string ~enc:(fun p -> p.email)
     |> finish))

(* Decode from XML *)
let () =
  match decode_string person "<person name=\"Alice\" age=\"30\"/>" with
  | Ok p -> Printf.printf "Name: %s, Age: %d\n" p.name p.age
  | Error e -> prerr_endline e

(* Encode to XML *)
let xml = encode_string ~indent:2 person { name = "Bob"; age = 25; email = None }

API Overview#

  • 'a t -- XML codec type (bidirectional)
  • string, int, float, bool -- Text content codecs
  • element -- Wrap a codec in a named XML element
  • Attr module -- Attribute-level codecs (Attr.string, Attr.int, Attr.float, Attr.option)
  • El module -- Element builder: obj, attr, child, child_opt, children, text, finish
  • map, const, option, list -- Codec combinators
  • decode_string, encode_string -- String I/O
  • decode, encode -- Streaming I/O via bytesrw readers/writers
  • Tree module -- Low-level XML tree access (escape hatch)
  • child, attr, nth -- Query combinators for navigating into structures

References#

  • Jsont -- The JSON codec library that inspired this approach
  • bytesrw -- Composable byte stream readers and writers

Licence#

ISC License. See LICENSE.md for details.