【发布时间】:2010-10-04 16:03:01
【问题描述】:
我创建了一个接受对象的方法,然后尝试将对象序列化为 Xml,首先使用 XmlSerializer 序列化为字符串,然后将 Xml 加载回 XmlDocument 对象以使该方法返回。代码如下所示;
public static XmlDocument ConvertObjectToXMLMessage(object ObjectToConvert)
{
MemoryStream stream = null;
XmlWriter writer = null;
XmlSerializer serializer = null;
XmlDocument xmlDoc = new XmlDocument();
UnicodeEncoding utf = new UnicodeEncoding();
UTF8Encoding utf8 = new UTF8Encoding();
ASCIIEncoding ascii = new ASCIIEncoding();
string result = string.Empty;
try
{
stream = new MemoryStream();
//writer = new StreamWriter(stream, Encoding.Unicode);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
writer = XmlWriter.Create(stream, settings);
serializer = new XmlSerializer(ObjectToConvert.GetType());
serializer.Serialize(writer, ObjectToConvert);
int count = Convert.ToInt32(stream.Length);
Byte[] arr = new Byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
result = utf8.GetString(arr).Trim();
// if this is being used during a debug session, the xml will be written to the Debug Console
#if DEBUG
//blank line before
Debug.WriteLine(string.Empty);
// output result
Debug.Write(result);
//blank line after
Debug.WriteLine(string.Empty);
#endif
xmlDoc.LoadXml(result);
return xmlDoc;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (writer != null)
writer.Close();
}
}
在 xmlDoc.LoadXml(result) 命令之前一切正常。这会引发异常; {"根级别的数据无效。第 1 行,位置 1。"}
如您所见,我已经声明了许多编码变量。如果我使用 ASCII 编码,它可以工作。我需要使用 UTF8。
任何想法为什么这不起作用?我认为这是因为在 Xml 序列化的开头插入了虚假字符。我该如何避免这种情况?我可以序列化的类类型是实体框架对象或从 XSD 或 WSDL 生成的代理类。
【问题讨论】:
标签: c# xml xml-serialization