Skip to content

Instantly share code, notes, and snippets.

@aantron
Last active October 4, 2018 17:19
Show Gist options
  • Save aantron/646740fc14801942679daa6109b11cc0 to your computer and use it in GitHub Desktop.
Save aantron/646740fc14801942679daa6109b11cc0 to your computer and use it in GitHub Desktop.
TyXML to Markup.ml
(* Note: `Raw signal is not released. I originally had assert false in the cases that use it. *)
let write_html_to_channel : Pervasives.out_channel -> Tyxml.Html.doc -> unit =
fun channel page ->
let ns name = (Markup.Ns.html, name) in
let convert_attributes attributes =
attributes |> List.map ~f:begin fun attribute ->
let value =
match Tyxml.Xml.acontent attribute with
| AFloat n -> Xml_print.string_of_number n
| AInt n -> string_of_int n
| AStr s -> s
| AStrL (Space, ss) -> String.concat ~sep:" " ss
| AStrL (Comma, ss) -> String.concat ~sep:", " ss
in
(ns (Tyxml.Xml.aname attribute), value)
end
in
Tyxml.Html.doc_toelt page
|> Markup.from_tree (fun html_node ->
match Tyxml.Xml.content html_node with
| Empty -> `Text ""
| Comment s -> `Comment s
| EncodedPCDATA s -> `Raw s
| PCDATA s -> `Text s
| Entity s -> `Raw ("&" ^ s ^ ";")
| Leaf (name, attributes) ->
`Element (ns name, convert_attributes attributes, [])
| Node (name, attributes, children) ->
`Element (ns name, convert_attributes attributes, children))
|> Markup.html5
|> Markup.write_html
|> Markup.to_channel channel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment