Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/String2XmlSerializer.cs @ 3036

Last change on this file since 3036 was 3036, checked in by epitzer, 14 years ago

make most serializers internal and complete API documentation (#548)

File size: 1.6 KB
Line 
1using System;
2using HeuristicLab.Persistence.Core;
3using HeuristicLab.Persistence.Interfaces;
4using System.Text;
5using System.Text.RegularExpressions;
6using System.Globalization;
7
8
9namespace HeuristicLab.Persistence.Default.Xml.Primitive {
10
11  /// <summary>
12  /// Serializes a string to XML by embedding into a CDATA block.
13  /// </summary>
14  public sealed class String2XmlSerializer : PrimitiveXmlSerializerBase<string> {
15
16    /// <summary>
17    /// Formats the specified string.
18    /// </summary>
19    /// <param name="s">The string.</param>
20    /// <returns>An XmlString that embeds the string s in a CDATA section.</returns>
21    public override XmlString Format(string s) {
22      StringBuilder sb = new StringBuilder();
23      sb.Append("<![CDATA[");
24      sb.Append(s.Replace("]]>", "]]]]><![CDATA[>"));
25      sb.Append("]]>");
26      return new XmlString(sb.ToString());
27    }
28
29    private static Regex re = new Regex(@"<!\[CDATA\[((?:[^]]|\](?!\]>))*)\]\]>", RegexOptions.Singleline);
30
31    /// <summary>
32    /// Parses the specified XmlString into a string.
33    /// </summary>
34    /// <param name="x">The XMLString.</param>
35    /// <returns>The plain string contained in the XML CDATA section.</returns>
36    public override string Parse(XmlString x) {
37      StringBuilder sb = new StringBuilder();
38      foreach (Match m in re.Matches(x.Data)) {
39        sb.Append(m.Groups[1]);
40      }
41      string result = sb.ToString();
42      if (result.Length == 0 && x.Data.Length > 0 && !x.Data.Equals("<![CDATA[]]>"))
43        throw new PersistenceException("Invalid CDATA section during string parsing.");
44      return result;
45    }
46  }
47}
Note: See TracBrowser for help on using the repository browser.