我有一些 biz 对象来存储客户名称,有时名称包含一些特殊字符,如
, 
。这些名称是从第 3 方导入的,我无法从源中删除有趣的字符。
应用程序会通过 XmlSerializer 对客户对象进行序列化/反序列化,但是这里奇怪的是,当我用特殊字符序列化名称时,没有错误,结果会是这样<Name>Jim <Name>
。但是当我反序列化输出 xml 时,我会得到一个异常There is an error in XML document (3, 15)
。
那么如何在我的应用程序中处理这些特殊字符呢?谢谢!
附上一些测试代码:
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);
}
}