1 | using System;
|
---|
2 | using HeuristicLab.Persistence.Core;
|
---|
3 | using HeuristicLab.Persistence.Interfaces;
|
---|
4 | using System.Text;
|
---|
5 | using System.Text.RegularExpressions;
|
---|
6 | using HeuristicLab.Persistence.Default.Decomposers.Storable;
|
---|
7 | using System.Globalization;
|
---|
8 |
|
---|
9 |
|
---|
10 | namespace HeuristicLab.Persistence.Default.Xml.Primitive {
|
---|
11 |
|
---|
12 | [EmptyStorableClass]
|
---|
13 | public class TimeSpan2XmlFormatter : PrimitiveXmlFormatterBase<TimeSpan> {
|
---|
14 |
|
---|
15 | public override XmlString Format(TimeSpan o) {
|
---|
16 | return new XmlString(o.ToString());
|
---|
17 | }
|
---|
18 |
|
---|
19 | public override TimeSpan Parse(XmlString t) {
|
---|
20 | try {
|
---|
21 | return TimeSpan.Parse(t.Data);
|
---|
22 | } catch (FormatException x) {
|
---|
23 | throw new PersistenceException("Cannot parse TimeSpan string representation.", x);
|
---|
24 | } catch (OverflowException x) {
|
---|
25 | throw new PersistenceException("Overflow during TimeSpan parsing.", x);
|
---|
26 | }
|
---|
27 | }
|
---|
28 | }
|
---|
29 |
|
---|
30 | [EmptyStorableClass]
|
---|
31 | public class Guid2XmlFormatter : PrimitiveXmlFormatterBase<Guid> {
|
---|
32 |
|
---|
33 | public override XmlString Format(Guid o) {
|
---|
34 | return new XmlString(o.ToString("D", CultureInfo.InvariantCulture));
|
---|
35 | }
|
---|
36 |
|
---|
37 | public override Guid Parse(XmlString t) {
|
---|
38 | try {
|
---|
39 | return new Guid(t.Data);
|
---|
40 | } catch (FormatException x) {
|
---|
41 | throw new PersistenceException("Cannot parse Guid string representation.", x);
|
---|
42 | } catch (OverflowException x) {
|
---|
43 | throw new PersistenceException("Overflow during Guid parsing.", x);
|
---|
44 | }
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | [EmptyStorableClass]
|
---|
49 | public class String2XmlFormatter : PrimitiveXmlFormatterBase<string> {
|
---|
50 |
|
---|
51 | public override XmlString Format(string s) {
|
---|
52 | StringBuilder sb = new StringBuilder();
|
---|
53 | sb.Append("<![CDATA[");
|
---|
54 | sb.Append(s.Replace("]]>", "]]]]><![CDATA[>"));
|
---|
55 | sb.Append("]]>");
|
---|
56 | return new XmlString(sb.ToString());
|
---|
57 | }
|
---|
58 |
|
---|
59 | public override string Parse(XmlString x) {
|
---|
60 | StringBuilder sb = new StringBuilder();
|
---|
61 | Regex re = new Regex(@"<!\[CDATA\[((?:[^]]|\](?!\]>))*)\]\]>", RegexOptions.Singleline);
|
---|
62 | foreach (Match m in re.Matches(x.Data)) {
|
---|
63 | sb.Append(m.Groups[1]);
|
---|
64 | }
|
---|
65 | string result = sb.ToString();
|
---|
66 | if (result.Length == 0 && x.Data.Length > 0 && !x.Data.Equals("<![CDATA[]]>"))
|
---|
67 | throw new PersistenceException("Invalid CDATA section during string parsing.");
|
---|
68 | return sb.ToString();
|
---|
69 | }
|
---|
70 | }
|
---|
71 | } |
---|