2011-05-07 44 views
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; 
      } 
     } 
    } 
    } 

回答

8

字符串代碼XmlWriter的輸出可能不完全當您調用StringWriter上的ToString()時會沖洗。嘗試在做之前先處理XmlWriter對象:

try 
{ 
    using (var stringWriter = new StringWriter()) 
    { 
     using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings)) 
     { 
      ds.WriteObject(xmlWriter, objectToSerialize); 
     } 
     return stringWriter.ToString(); 
    } 
} 
catch (Exception ex) 
{ 
    return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message; 
} 
+1

+1:謝謝你的工作解決方案。而不是在'return stringWriter.ToString();'之前配置'xmlWriter.Flush();'也行。 – k3b 2011-05-08 06:10:08

相關問題