print_xml.ml 1.96 KB
Newer Older
1 2 3 4 5
(* Print XML documents, using PXP *)

open Pxp_aux
open Pxp_types
open Value
6
open Ident
7
module U = Encodings.Utf8
8

9
let exn_print_xml = CDuceExn (Pair (
10
				Atom (Atoms.mk_ascii "Invalid_argument"),
11
				string_latin1 "print_xml"))
12

13 14 15 16
let string_of_xml ~enc v= 
  let to_enc = match enc with
    | `Utf8 -> `Enc_utf8
    | `Latin1 -> `Enc_iso88591 in
17 18 19 20 21

  let buffer = Buffer.create 127 in

  let wms = 
    write_markup_string
22
      ~from_enc:`Enc_utf8 
23 24 25
      ~to_enc
      (`Out_buffer buffer)

26
  and wds s =
27
    write_data_string
28
      ~from_enc:`Enc_utf8
29 30
      ~to_enc
      (`Out_buffer buffer)
31
      (U.get_str s)
32
  in
33
  let write_att (n,v) = wms (" " ^ (U.get_str n) ^ "=\""); wds v; wms "\"" in
34
  let element_start name attrs = 
35
    wms ("<" ^ (U.get_str name)); List.iter write_att attrs; wms ">"
36
  and empty_element name attrs = 
37 38
    wms ("<" ^ (U.get_str name)); List.iter write_att attrs; wms "/>"
  and element_end name = wms ("</" ^ (U.get_str name) ^ ">")
39
  and document_start () = 
40
(*    wms ("<?xml version='1.0' encoding='" ^
41
	 Netconversion.string_of_encoding to_enc ^
42 43
	 "'?>\n") *)
      ()
44
  in
45 46

  let rec print_elt = function
47
    | Xml (Atom tag, Pair (Record attrs, content)) ->
48
	let tag = Atoms.value tag in
49 50 51
	let attrs = LabelMap.mapi_to_list 
		      (fun n v -> 
			 if not (is_str v) then raise exn_print_xml;
52 53 54 55 56
			 let (s,q) = get_string_utf8 v in
			 match q with
			   | Atom a when a = Sequence.nil_atom -> LabelPool.value n, s
			   | _ -> raise exn_print_xml
		      ) attrs in
57 58 59 60 61 62
	(match content with
	  | Atom a when a = Sequence.nil_atom -> empty_element tag attrs
	  | _ ->
	      element_start tag attrs;
	      print_content content;
	      element_end tag)
63
    | _ -> raise exn_print_xml
64 65 66 67 68 69 70
  and print_content v =
    let (s,q) = get_string_utf8 v in
    wds s;
    match q with
      | Pair (x, q) -> print_elt x; print_content q
      | Atom a when a = Sequence.nil_atom -> ()
      | _ -> raise exn_print_xml
71 72 73 74
  in
  document_start ();
  print_elt v;
  Buffer.contents buffer