Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Default/Xml/XmlGenerator.cs @ 1363

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

Convenience method for XML serialization and de-serizliation. (#506)

File size: 5.3 KB
Line 
1using System.Collections.Generic;
2using System;
3using System.Text;
4using HeuristicLab.Persistence.Interfaces;
5using HeuristicLab.Persistence.Core;
6using System.IO;
7
8namespace HeuristicLab.Persistence.Default.Xml {
9
10  struct XmlStrings {
11    public const string PRIMITIVE = "PRIMITVE";
12    public const string COMPOSITE = "COMPOSITE";
13    public const string REFERENCE = "REFERENCE";
14    public const string NULL = "NULL";
15    public const string TYPECACHE = "TYPCACHE";
16    public const string TYPE = "TYPE";
17  }
18 
19  public class XmlGenerator {
20   
21    delegate string Formatter(ISerializationToken token);
22
23    private readonly Dictionary<Type, Formatter> formatters;
24    private int depth;
25
26    public XmlGenerator() {
27      formatters = new Dictionary<Type, Formatter>{
28                       {typeof (BeginToken), FormatBegin},
29                       {typeof (EndToken), FormatEnd},
30                       {typeof (PrimitiveToken), FormatPrimitive},
31                       {typeof (ReferenceToken), FormatReference},
32                       {typeof (NullReferenceToken), FormatNullReference}
33                     };
34      depth = 0;
35    }
36
37    private enum NodeType { Start, End, Inline } ;
38
39    private static string FormatNode(string name,
40        Dictionary<string, object> attributes,
41        NodeType type) {
42      return FormatNode(name, attributes, type, " ");
43    }
44
45    private static string FormatNode(string name,
46        Dictionary<string, object> attributes,
47        NodeType type, string space) {
48      StringBuilder sb = new StringBuilder();
49      sb.Append('<');
50      if (type == NodeType.End)
51        sb.Append('/');
52      sb.Append(name);     
53      foreach (var attribute in attributes) {
54        if (attribute.Value != null && !string.IsNullOrEmpty(attribute.Value.ToString())) {
55          sb.Append(space);
56          sb.Append(attribute.Key);
57          sb.Append("=\"");
58          sb.Append(attribute.Value);
59          sb.Append('"');
60        }
61      }
62      if (type == NodeType.Inline)
63        sb.Append('/');
64      sb.Append(">");
65      return sb.ToString();     
66    }
67
68    public string Format(ISerializationToken token) {
69      return formatters[token.GetType()](token);
70    }
71
72    private string Prefix {
73      get { return new string(' ', depth * 2); }
74    }
75
76    private string FormatBegin(ISerializationToken token) {     
77      BeginToken beginToken = (BeginToken)token;
78      var attributes = new Dictionary<string, object> {
79        {"name", beginToken.Name},
80        {"typeId", beginToken.TypeId},
81        {"id", beginToken.Id}};
82      string result = Prefix +
83                      FormatNode(XmlStrings.COMPOSITE, attributes, NodeType.Start) + "\n";
84      depth += 1;
85      return result;
86    }
87
88    private string FormatEnd(ISerializationToken token) {     
89      depth -= 1;
90      return Prefix + "</" + XmlStrings.COMPOSITE + ">\n";
91    }
92
93    private string FormatPrimitive(ISerializationToken token) {
94      PrimitiveToken dataToken = (PrimitiveToken)token;
95      var attributes =
96        new Dictionary<string, object> {
97            {"typeId", dataToken.TypeId},
98            {"name", dataToken.Name},
99            {"id", dataToken.Id}};
100      return Prefix +
101        FormatNode(XmlStrings.PRIMITIVE, attributes, NodeType.Start) +
102        dataToken.SerialData + "</" + XmlStrings.PRIMITIVE + ">\n";     
103    }
104
105    private string FormatReference(ISerializationToken token) {
106      ReferenceToken refToken = (ReferenceToken) token;
107      var attributes = new Dictionary<string, object> {
108        {"ref", refToken.Id},
109        {"name", refToken.Name}};                                       
110      return Prefix + FormatNode(XmlStrings.REFERENCE, attributes, NodeType.Inline) + "\n"; 
111    }
112
113    private string FormatNullReference(ISerializationToken token) {
114      NullReferenceToken nullRefToken = (NullReferenceToken)token;
115      var attributes = new Dictionary<string, object>{
116        {"name", nullRefToken.Name}};     
117      return Prefix + FormatNode(XmlStrings.NULL, attributes, NodeType.Inline) + "\n";
118    }
119
120    public IEnumerable<string> Format(List<TypeMapping> typeCache) {
121      yield return "<" + XmlStrings.TYPECACHE + ">";
122      foreach (var mapping in typeCache)
123        yield return "  " + FormatNode(
124          XmlStrings.TYPE,
125          mapping.GetDict(),
126          NodeType.Inline,
127          "\n    ");
128      yield return "</" + XmlStrings.TYPECACHE + ">";
129    }
130
131    public static void Serialize(object o, string basename) {     
132      Serialize(o, basename, ConfigurationService.Instance.GetDefaultConfig(XmlFormat.Instance));
133    }
134
135    public static void Serialize(object o, string basename, Configuration configuration) {
136    Serializer s = new Serializer(o, configuration);
137      XmlGenerator xmlGenerator = new XmlGenerator();
138      StreamWriter writer = new StreamWriter(basename + ".xml");
139      foreach (ISerializationToken token in s) {
140        string line = xmlGenerator.Format(token);
141        writer.Write(line);
142        Console.Out.Write(line);
143      }
144      writer.Close();
145      writer = new StreamWriter(basename + "-types.xml");
146      foreach (string line in xmlGenerator.Format(s.TypeCache)) {
147        writer.WriteLine(line);
148        Console.Out.WriteLine(line);
149      }
150      writer.Close();     
151    }
152
153  }
154}
Note: See TracBrowser for help on using the repository browser.