Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/XmlFormatter.cs @ 1280

Last change on this file since 1280 was 1280, checked in by epitzer, 15 years ago

Split classes into more files. (#506)

File size: 2.3 KB
Line 
1using System.Collections.Generic;
2using System;
3namespace Persistence {
4  public class XmlFormatter {
5
6    delegate string Formatter(ISerializationToken token);
7
8    private Dictionary<Type, Formatter> formatters;
9    private int depth;
10
11    public XmlFormatter() {
12      this.formatters = new Dictionary<Type, Formatter>();
13      this.formatters.Add(typeof(BeginToken), new Formatter(FormatBegin));
14      this.formatters.Add(typeof(EndToken), new Formatter(FormatEnd));
15      this.formatters.Add(typeof(PrimitiveToken), new Formatter(FormatData));
16      this.formatters.Add(typeof(ReferenceToken), new Formatter(FormatReference));
17      this.formatters.Add(typeof(NullReferenceToken), new Formatter(FormatNullReference));
18      this.depth = 0;
19    }
20
21    public string Format(ISerializationToken token) {
22      return formatters[token.GetType()](token);
23    }
24
25    private string Prefix {
26      get { return new string(' ', this.depth * 2); }
27    }
28
29    private string FormatBegin(ISerializationToken token) {
30      BeginToken beginToken = (BeginToken)token;
31      string result =
32        String.Format("{0}<COMPOSITE name=\"{1}\" type=\"{2}\" id=\"{3}\">\n",
33          this.Prefix, beginToken.Accessor.Name, beginToken.Accessor.Type, beginToken.Id);
34      this.depth += 1;
35      return result;
36    }
37
38    private string FormatEnd(ISerializationToken token) {
39      EndToken endToken = (EndToken)token;
40      this.depth -= 1;
41      return Prefix + "</COMPOSITE>\n";
42    }
43
44    private string FormatData(ISerializationToken token) {
45      PrimitiveToken dataToken = (PrimitiveToken)token;
46      return String.Format("{0}<PRIMITIVE name=\"{1}\" type=\"{2}\">{3}</PRIMITIVE>\n",
47        this.Prefix, dataToken.accessor.Name, dataToken.accessor.Type, dataToken.Data);
48    }
49
50    private string FormatReference(ISerializationToken token) {
51      ReferenceToken refToken = (ReferenceToken)token;
52      return String.Format("{0}<REFERENCE name=\"{1}\" ref=\"{2}\"/>\n",
53        this.Prefix, refToken.Name, refToken.Id);
54    }
55
56    private string FormatNullReference(ISerializationToken token) {
57      NullReferenceToken nullRefToken = (NullReferenceToken)token;
58      return String.Format("{0}<NULL name=\"{1}\"/>\n",
59        this.Prefix, nullRefToken.Name);
60    }
61  }
62}
Note: See TracBrowser for help on using the repository browser.