[英]Missing the end of the XML when serializing with DataContractSerializer
I have the following method that I use to serialize various objects to XML. 我有以下方法用于将各种对象序列化为XML。 I then write the XML to a file.
然后我将XML写入文件。 All the objects have the proper
[DataContract]
and [DataMember]
attributes. 所有对象都具有适当的
[DataContract]
和[DataMember]
属性。
public static string Serialize<T>(T item)
{
var builder = new StringBuilder();
var serializer = new DataContractSerializer(typeof(T));
using (var xmlWriter = XmlWriter.Create(builder))
{
serializer.WriteObject(xmlWriter, item);
return builder.ToString();
}
}
The serialization works fine, however, I am missing the end of the content. 序列化工作正常,但是,我错过了内容的结尾。 Ie, the string does not contain the full XML document: the end gets truncated.
即,字符串不包含完整的XML文档:结尾被截断。 Sometimes the string ends right in the middle of a tag.
有时,字符串会在标记的中间结束。
There does not seem to be a miximum length that would cause an issue: I have strings of 18k that are incomplete and I have strings of 80k that are incomplete as well. 似乎没有混合长度会导致问题:我有18k的字符串是不完整的,我有80k的字符串也是不完整的。
The XML structure is fairly simple and only about 6-8 nodes deep. XML结构非常简单,只有大约6-8个节点。
Am I missing something? 我错过了什么吗?
xmlWriter
isn't flushed at the point you call ToString()
; 在调用
ToString()
,不会刷新xmlWriter
; try: 尝试:
using (var xmlWriter = XmlWriter.Create(builder))
{
serializer.WriteObject(xmlWriter, item);
}
return builder.ToString();
This does the ToString()
after the Dispose()
on xmlWriter
, meaning it will flush any buffered data to the output ( builder
in this case). 这在
xmlWriter
上的Dispose()
ToString()
之后执行ToString()
,这意味着它会将任何缓冲的数据刷新到输出(在本例中为builder
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.