1 | using System.Collections.Generic;
|
---|
2 | using System;
|
---|
3 | namespace Persistence {
|
---|
4 | public class XmlFormatter {
|
---|
5 |
|
---|
6 | delegate string Formatter(ISerializationToken token);
|
---|
7 |
|
---|
8 | private readonly Dictionary<Type, Formatter> formatters;
|
---|
9 | private int depth;
|
---|
10 |
|
---|
11 | public XmlFormatter() {
|
---|
12 | formatters = new Dictionary<Type, Formatter>{
|
---|
13 | {typeof (BeginToken), FormatBegin},
|
---|
14 | {typeof (EndToken), FormatEnd},
|
---|
15 | {typeof (PrimitiveToken), FormatData},
|
---|
16 | {typeof (ReferenceToken), FormatReference},
|
---|
17 | {typeof (NullReferenceToken), FormatNullReference}
|
---|
18 | };
|
---|
19 | depth = 0;
|
---|
20 | }
|
---|
21 |
|
---|
22 | public string Format(ISerializationToken token) {
|
---|
23 | return formatters[token.GetType()](token);
|
---|
24 | }
|
---|
25 |
|
---|
26 | private string Prefix {
|
---|
27 | get { return new string(' ', depth * 2); }
|
---|
28 | }
|
---|
29 |
|
---|
30 | private string FormatBegin(ISerializationToken token) {
|
---|
31 | BeginToken beginToken = (BeginToken)token;
|
---|
32 | string result =
|
---|
33 | String.Format("{0}<COMPOSITE name=\"{1}\" type=\"{2}\" id=\"{3}\">\n",
|
---|
34 | Prefix, beginToken.Accessor.Name, beginToken.Accessor.Get().GetType(), beginToken.Id);
|
---|
35 | depth += 1;
|
---|
36 | return result;
|
---|
37 | }
|
---|
38 |
|
---|
39 | private string FormatEnd(ISerializationToken token) {
|
---|
40 | 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 | Prefix, dataToken.accessor.Name, dataToken.accessor.Get().GetType(), 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 | 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 | Prefix, nullRefToken.Name);
|
---|
60 | }
|
---|
61 | }
|
---|
62 | } |
---|