我正在使用这段代码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();
}
问题是我得到:
<?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>
有什么办法可以改变<?xml version="1.0" encoding="utf-16"?>
to
<?xml version="1.0" encoding="utf-8"?>
?
这是一个以编码作为参数的代码。请阅读注释为什么有 SuppressMessage 进行代码分析。
/// <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());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)