Hi Pete,

It seems to me the code to use the XmlSerializer was wrong, it didn't compile for me, but I'm guessing thats just because you were playing arround trying to get to work. You can't use the xml serializer with some F# types as generally types that work with the XML serializer need to be crafted to serialize correctly. Often the best apporach is design the objects you want serializer as xsd schema then create .NET classes with these using the xsd.exe tool packaged with the .NET sdk. (You see that the classes generated are covered in .NET attribtutes to ensure they serializer correctly, you can do this by hand with F# class types but obviously this is time consuming).

I know the apporach of designing objects in as xsd schema won't work too well for an AST, but for storing your AST I think your just going to have to stick to the binary formatter.

Cheers,
Rob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#light
open System.IO
open System.Xml
open System.Xml.Serialization
open System.Runtime.Serialization.Formatters.Binary

type Expr = 
  | Val of string 
  | Float of System.Double
  | Multi of Expr * Expr
  | Div of Expr * Expr
  | Plus of Expr * Expr
  | Minus of Expr * Expr

let tree = Multi ( Float (7.0), Float (3.0) )

let xmlSerializeObject<'T> (file : string) (objectToSerialize : 'T) = 
  using (new StreamWriter(file)) (fun fs ->
  let xmlWriter = new XmlTextWriter(fs)
  let xs = new System.Xml.Serialization.XmlSerializer((type 'T))
  xs.Serialize (xmlWriter, objectToSerialize))

let xmlDeserializeObject<'T> (file : string) = 
  using (new StreamReader(file)) (fun fs ->
  let xmlReader = new XmlTextReader(fs)
  let xs = new System.Xml.Serialization.XmlSerializer((type 'T))
  xs.Deserialize (xmlReader) :?> 'T)

let serializeObject (file : string) objectToSerialize = 
  using (File.OpenWrite(file)) (fun fs ->
  let bf = new BinaryFormatter()
  bf.Serialize (fs, objectToSerialize))

let deserializeObject (file : string) = 
  using (File.OpenRead(file)) (fun fs ->
  let bf = new BinaryFormatter()
  bf.Deserialize (fs))

serializeObject "tree.ats" tree

let tree2 = (deserializeObject "tree.ats") :?> Expr

printf "tree: %O\r\n" tree
printf "tree2: %O\r\n" tree2
read_line()
By on 6/12/2007 12:38 AM ()

Rob,

Thanks for the practical help and adivice on XML serialization.

Pete

By on 6/12/2007 12:20 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper