C# Xml Serialization & Deserialization

浪子不回头ぞ 提交于 2019-11-27 14:25:47

In your deserialization code you're creating a MemoryStream and XmlTextWriter but you're not giving it the string to deserialize.

using (MemoryStream memStream = new MemoryStream())
{
    using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
    {
        // Omitted
    }
}

You can pass the bytes to the memory stream and do away with the XmlTextWriter altogether.

using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(memStream);
}

Looks like you got a handle on serializing to XML, so take my advice, store the XML in a string field (varchar, nvarchar, text, ntext) and not a specialized field.

If you do that little switch you will be ready to go... no further modification required.

XML field is subject to validations, and more than a few headaches, and if your application is only producer and consumer of that field, you might as well take that shortcut. SQL2008 (even 2005) is strong enough to compensate for the resources you might save by it compiling the xml field.

HOWEVER , I would optimize your code a bit, looks like you wrote way more code than you had to. For example, you no longer need to create a private field to store the data from your property, for example :

public PersonalXml Personal
{
    get { return _personal; }
    set { _personal = value; }
}

will work just fine if you wrote it like :

    public PersonalXml Personal { get ; set ; }

there's more fat you could have cut...

I believe that you need to add the XML header:

<?xml version="1.0" encoding="utf-8" ?>

You could modify your serialize method to accept an optional parameter that would cause this to be added:

public static string Serialize<T>(T item, bool includeHeader = false)
{
    MemoryStream memStream = new MemoryStream();
    using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        serializer.Serialize(textWriter, item);

        memStream = textWriter.BaseStream as MemoryStream;
    }
    if (memStream != null)
        if (includeHeader)
        {
            return @"<?xml version=""1.0"" encoding=""utf-8"" ?>" + Environment.NewLine + Encoding.Unicode.GetString(memStream.ToArray());
        }
        else
        {
            return Encoding.Unicode.GetString(memStream.ToArray());
        }
    else
        return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!