5
我正在使用DataContractSerializer
将EF4对象序列化为xml(如果有例外)。 在我的调试日志中,当出现问题时,我可以看到想要的是数据内容。为什么DataContractSerializer要截断StringWriter?
我有两个版本的代码:一个版本串行化为一个文件,一个串行化为一个字符串,使用StringWriter
。
当序列化大项目文件我得到约16kb的有效xml。 当序列化相同的项目来串xml被截断后12kb。任何想法是什么导致了截断?
...
var entity = ....
SaveAsXml(entity, @"c:\temp\EntityContent.xml"); // ok size about 16100 btes
var xmlString = GetAsXml(entity); // not ok, size about 12200 bytes
// to make shure that it is not Debug.Writeline that causes the truncation
// start writing near the end of the string
// only 52 bytes are written although the file is 16101 bytes long
System.Diagnostics.Debug.Writeline(xml.Substring(12200));
为什么我的字符串被截断,任何想法?
下面是序列化到文件中的代码工作正常
public static void SaveAsXml(object objectToSave, string filenameWithPath)
{
string directory = Path.GetDirectoryName(filenameWithPath);
if (!Directory.Exists(directory))
{
logger.Debug("Creating directory on demand " + directory);
Directory.CreateDirectory(directory);
}
logger.DebugFormat("Writing xml to " + filenameWithPath);
var ds = new DataContractSerializer(objectToSave.GetType(), null, Int16.MaxValue, true, true, null);
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NamespaceHandling = NamespaceHandling.OmitDuplicates,
NewLineOnAttributes = true,
};
using (XmlWriter w = XmlWriter.Create(filenameWithPath, settings))
{
ds.WriteObject(w, objectToSave);
}
}
这里是序列化到将被截断
public static string GetAsXml(object objectToSerialize)
{
var ds = new DataContractSerializer(objectToSerialize.GetType(), null, Int16.MaxValue, true, true, null);
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NamespaceHandling = NamespaceHandling.OmitDuplicates,
NewLineOnAttributes = true,
};
using (var stringWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
{
try
{
ds.WriteObject(xmlWriter, objectToSerialize);
return stringWriter.ToString();
}
catch (Exception ex)
{
return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message;
}
}
}
}
+1:谢谢你的工作解决方案。而不是在'return stringWriter.ToString();'之前配置'xmlWriter.Flush();'也行。 – k3b 2011-05-08 06:10:08