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

open Pxp_aux
open Pxp_types
open Value

7
8
9
let exn_print_xml = CDuceExn (Pair (
				Atom (Types.AtomPool.mk "Invalid_argument"),
				string "print_xml"))
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32


let to_enc = `Enc_iso88591

let string_of_xml v= 
  let buffer = Buffer.create 127 in

  let wms = 
    write_markup_string
      ~from_enc:`Enc_iso88591 
      ~to_enc
      (`Out_buffer buffer)

  and wds =
    write_data_string
      ~from_enc:`Enc_iso88591 
      ~to_enc
      (`Out_buffer buffer)
  in
  let comment s = wms ("<!--" ^ s ^ "-->")
  and write_att (n,v) = wms (" " ^ n ^ "=\""); wds v; wms "\"" in
  let element_start name attrs = 
    wms ("<" ^ name); List.iter write_att attrs; wms "\n>"
33
34
  and empty_element name attrs = 
    wms ("<" ^ name); List.iter write_att attrs; wms "/>"
35
36
  and element_end name = wms ("</" ^ name ^ "\n>")
  and document_start () = 
37
(*    wms ("<?xml version='1.0' encoding='" ^
38
	 Netconversion.string_of_encoding to_enc ^
39
40
	 "'?>\n") *)
      ()
41
42
43
  and text s = wds s in

  let rec print_elt = function
44
    | Xml (Atom tag, Pair (Record attrs, content)) ->
45
	let tag = Types.AtomPool.value tag in
46
	let attrs = List.map (fun (n,v) -> 
47
		       if not (is_str v) then raise exn_print_xml;
48
49
50
51
52
53
54
		       (Types.LabelPool.value n,get_string v)) attrs in
	(match content with
	  | Atom a when a = Sequence.nil_atom -> empty_element tag attrs
	  | _ ->
	      element_start tag attrs;
	      print_content content;
	      element_end tag)
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    | Char x ->
 	wds (String.make 1 (Chars.Unichar.to_char x)); (* TODO: opt *)
   | _ -> raise exn_print_xml
  and print_content = function
    | String (i,j,s,q) ->
	wds (String.sub s i (j - i));
	print_content q
    | Pair (elt, q) ->
	print_elt elt;
	print_content q
    | Atom a when a = Sequence.nil_atom -> true
    | _ -> raise exn_print_xml
  in
  document_start ();
  print_elt v;
  Buffer.contents buffer