C#XmlSerializer序列化/反序列化特殊字符

时间:2018-01-19 07:49:37

标签: c# serialization xmlserializer

我发现XmlSerializer在序列化/反序列化对象时无法正确处理char,抱歉我无法在此处输入,请参见下图。

在序列化/反序列化时,有人知道如何处理这样的字符吗?

非常感谢!

enter image description here enter image description here

我的代码示例: 实体类定义:

public class Entity
{
    public string value;

    public override string ToString()
    {
        return string.Format("Entity.Value: {0}", this.value);
    }
}

根据实体类型创建XmlSerializer对象:

private XmlSerializer GetXmlSerializer()
{
    xmlSerializer = default(XmlSerializer);

    Type type = typeof(Entity);
    IEnumerable<Type> types = new List<Type> { type };

    xmlSerializer = new XmlSerializer(type, types.ToArray());

    return xmlSerializer;
}

序列化Entity对象的代码:

private void BT_Serialize_Click(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
    {
        xmlSerializer.Serialize(sw, entity);
        string result = sw.ToString();
    }
}

基于XML序列化反序列化实体对象的代码(我可以手动更改):

private void BT_Deserialize_Click(object sender, EventArgs e)
{
    using (StringReader sr = new StringReader(xml))
    {
        object obj = xmlSerializer.Deserialize(sr);

        Entity entity = obj as Entity;
    }
}

0 个答案:

没有答案