xml序列化和反序列化字符串指定格式UTF-8

使用c#序列化和反序列化xml是非常简单的,但注意序列化字符串指定文本编码格式需要使用流的形式,否则编码格式设置无效。因此在一些需要设置编码格式的场景,使用流Stream来操作xml序列化和反序列化。代码如下:

/// <summary>
/// 数据输入,反序列化xml为对象
/// </summary>
/// <param name="XmlString"></param>
/// <returns></returns>
public string FileInput(string XmlString) 
{
    string InputResult = "";
    using (MemoryStream MS = new MemoryStream(Encoding.UTF8.GetBytes(XmlString))) 
    {
        using (XmlReader xr = XmlReader.Create(MS)) 
        {
            XmlSerializer xmlSearializer = new XmlSerializer(typeof(CobraInput));
            InputData = (CobraInput)xmlSearializer.Deserialize(xr);
            InputResult = "Read XML Success";
        }
    }
    return InputResult;
}
/// <summary>
/// 数据输出,序列化xml文本 
/// </summary>
/// <returns></returns>
public string FileOutput() 
{
    using (MemoryStream ms = new MemoryStream()) 
    {
        var setting = new XmlWriterSettings() 
        {
            Encoding = new UTF8Encoding(false),
                                Indent = true,
                            };
            using (XmlWriter writer = XmlWriter.Create(ms, setting)) 
            {
                XmlSerializer xmlSearializer = new XmlSerializer(typeof(CobraOutput));
                xmlSearializer.Serialize(writer, OutputData);
                OutputXmlString = Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        return OutputXmlString;
    }

作者:songshizhao 发表于:2017-10-27T01:04:51 访问量:1957