XmlSerializer的变化编码 [英] XmlSerializer change encoding

查看:117
本文介绍了XmlSerializer的变化编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这code到序列化 XML来字符串

I am using this code to Serialize XML to String:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
    indent = true,
    Encoding = Encoding.UTF8
};

using (var sw = new StringWriter())
{
    using (XmlWriter xmlWriter = XmlWriter.Create(sw, xmlWriterSettings))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(moviesObject.GetType(), new XmlRootAttribute("category"));
        xmlSerializer.Serialize(xmlWriter, moviesObject);
    }
    return sw.ToString();
}

现在的问题是,我得到的:

The problem is that i get :

<?xml version="1.0" encoding="utf-16"?>
<category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" havemore="no">
  <items>
    <movie>
      <videoid>videoid1</videoid>
      <title>title1</title>
    </movie>
  </items>
</category>

有什么办法可以修改&LT;?XML版本=1.0编码=UTF-16&GT; &LT; XML版本=1.0编码=UTF-8&GT; <?/ code>

There is any way to change the <?xml version="1.0" encoding="utf-16"?> to <?xml version="1.0" encoding="utf-8"?> ?

推荐答案

下面是一个code与编码作为参数。请阅读评论为什么有燮pressMessage为code分析。

Here is a code with encoding as parameter. Please read the comments why there is a SuppressMessage for code analysis.

/// <summary>
/// Serialize an object into an XML string
/// </summary>
/// <typeparam name="T">Type of object to serialize.</typeparam>
/// <param name="obj">Object to serialize.</param>
/// <param name="enc">Encoding of the serialized output.</param>
/// <returns>Serialized (xml) object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal static String SerializeObject<T>(T obj, Encoding enc)
{
    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings()
        {
            // If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose
            // Code analysis does not understand that. That's why there is a suppress message.
            CloseOutput = false, 
            Encoding = enc,
            OmitXmlDeclaration = false,
            Indent = true
        };
        using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
        {
            XmlSerializer s = new XmlSerializer(typeof(T));
            s.Serialize(xw, obj);
        }

        return enc.GetString(ms.ToArray());
    }
}

这篇关于XmlSerializer的变化编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆