How to serialize a data of type string without using StringWriter as input
I want to serialize a input data of type string, but do not want to use StringWriter and StringReader for for serializing/Deserializing. The reason for this is when a escapse chars are sent as part of the Input string for serializing, it is serialized but some Spl chars are inserted in the xml(eg:"").I'm getting an XMl error while deserializing this serialized data.
void M1()
{
string str = 23 + "AC"+(char)1;
StringWriter sw = new StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(String));
serializer.Serialize(sw, str);
System.Console.WriteLine("String encoded to XML = \n{开发者_Go百科0} \n", sw.ToString());
StringReader sr = new StringReader(sw.ToString());
String s2 = (String)serializer.Deserialize(sr);
System.Console.WriteLine("String decoded from XML = \n {0}", s2);
}
You can for example encode the string as UTF-8, then encode the data using base-64:
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(theString));
This gives you a string without any special characters.
Deserialising is the reverse:
string theString = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
How about using XmlWriter to write with and XmlTextReader to read with? Example:
var sb = new StringBuilder();
// set the encoding here: you may need to try different encoding types...
var settings = new XmlWriterSettings{ Encoding = System.Text.Encoding.UTF8 };
using (var writer = XmlWriter.Create(sb, settings))
{
string str = 23 + "AC"+(char)1;
XmlSerializer serializer = new XmlSerializer(typeof(String));
serializer.Serialize(writer, str);
System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString());
// more code to handle read the values with XmlTextReader, etc etc etc......
}
精彩评论