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 | |
---|
1 | using System;
|
---|
2 | using HeuristicLab.Persistence.Core;
|
---|
3 | using HeuristicLab.Persistence.Interfaces;
|
---|
4 | using System.Text;
|
---|
5 | using System.Text.RegularExpressions;
|
---|
6 | using System.Globalization;
|
---|
7 |
|
---|
8 |
|
---|
9 | namespace 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.