0
我如何使用CData序列化一個屬性?我已經嘗試了幾種不同的方法,包括使原始屬性XmlIgnore和引入返回XmlCDataSection的屬性。目前爲止沒有任何工作。如何爲CData屬性?
我有以下runnable控制檯測試顯示錯誤。我如何修改這個以允許正則表達式數據序列化和反序列化。
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public class MyRegex
{
public string Regex { get; set; }
}
public static class SerializerHelper<T>
{
public static string Serialize(T myobject)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, myobject);
string xml = stringWriter.ToString();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
return sw.ToString();
}
public static T DeSerialize(string xml)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(xml);
return (T)xmlSerializer.Deserialize(stringReader);
}
}
class Program
{
static void Main(string[] args)
{
MyRegex original = new MyRegex { Regex = "\b[1-3]{1}\b#Must be a value of 1 to 3" };
string xml = SerializerHelper<MyRegex>.Serialize(original);
Console.WriteLine("--- SERIALIZE ---");
Console.WriteLine(xml);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("--- DESERIALIZE ---");
MyRegex deSerial = SerializerHelper<MyRegex>.DeSerialize(xml);
Console.WriteLine("Equals? " + (deSerial.Regex.Equals(original.Regex)));
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Console.ReadKey();");
Console.ReadKey();
}
}
}
附加:試圖更換方法 - 不工作
private string _regex;
public string Regex
{
get { return _regex.Replace(@"\\", @"\").Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("'", "'"); }
set { _regex = value.Replace(@"\", @"\\").Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'"); }
}
的問題在於,在序列化時,無論\ b或\\ b將嘗試序列化爲對XML無效的。所以我需要CDATA它。正則表達式 - ' [1-3] {1} #必須是1到3的值'RegexEscaped' \\ [1-3] \\ {1} \\必須\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 3 \ \ –
CDATA不會幫助您將0-31字符放在XML中...... –
那麼,當我使用以下序列化函數中字符串xml下的黑客行。有用! \t \t \t'xml = xml.Replace(「」,「<![CDATA [」);' and'xml = xml.Replace(「 RegexString>」,「]]> RegexString>」 );'那我怎麼一般地做這個? –