I have some biz objects to store the customer names, sometimes the name contains some special characters like 
, 
. These names are imported from 3rd party, and I cannot delete the funny chars from the source.
The application will serialize/deserialize the customer object by XmlSerializer, but the strange thing here is when I serialize the name with special chars, there are no errors, and the result will be like this <Name>Jim <Name>
. But when I deserialize the output xml, I will get an exception There is an error in XML document (3, 15)
.
So how to handle these special characters in my application? Thanks!
Attached some test code:
public class Customer
{
public string Name;
}
class Program
{
public static T DeserializeFromXml<T>(string settings) where T : class
{
var serializer = new XmlSerializer(typeof(T));
var reader = new StringReader(settings);
var result = serializer.Deserialize(reader);
return result as T;
}
public static string SerializeToXml<T>(T settings)
{
var serializer = new XmlSerializer(typeof(T));
var writer = new StringWriter();
serializer.Serialize(writer, settings);
return writer.ToString();
}
static void Main(string[] args)
{
var str = new char[] { 'J', 'i', 'm', (char)2 };
var customer = new Customer { Name = new string(str) };
var output = SerializeToXml(customer);
var obj = DeserializeFromXml<Customer>(output);
}
}