View Category
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
ocaml
let () =
let xml = Xml.parse_file "shopping.xml" in
let res =
Xml.fold (fun total xml ->
match xml with
| Xml.Element ("item", attrs, _) ->
let quantity = float_of_string (List.assoc "quantity" attrs)
and price = float_of_string (List.assoc "price" attrs) in
total +. (quantity *. price)
| _ -> total
) 0.0 xml
in
Printf.printf "Total cost of the items: %g\n" res

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
ocaml
(* Compilation (native):
$ ocamlopt -I +csv csv.cmxa -I +xml-light xml-light.cmxa csv2xml.ml -o csv2xml
*)

let () =
let table = Csv.load "shopping.csv" in
let columns = ["name"; "quantity"; "price"] in

let xml = Xml.Element ("shopping", [],
List.rev (
List.fold_left (fun acc row ->
Xml.Element ("item",
List.combine columns row, []) :: acc) [] table)) in

print_endline (Xml.to_string_fmt xml)