XmlDocument.Load(xml)从XmlSerializer序列化代码生成无根元素错误

时间:2010-07-27 20:42:47

标签: c# visual-studio-2005 xml-serialization

我有一个类似的课程:

[XmlRoot"MyMessageType")]
public class MyMessageType : BaseMessageType
{
    [XmlElement("MessageId")]
    //Property for MessageId

    ...
    <snip>

    //end properties.
}

此类包含一个静态方法,用于创建要传递给BizTalk服务器的XmlDocument实例。像这样:

public static XmlDocument GetMyMessageType(string input1, string input2 ...)

GetMyMessageType创建一个MyMessageType实例,然后调用以下代码:

XmlSerializer outSer = new XmlSerializer(instance.GetType());
using (MemoryStream mem = new MemoryStream())
using (XmlWriter _xWrite = XmlWriter.Create(mem))
{
  outSer.Serialize(_xWrite, instance);
  XmlDocument outDoc = new XmlDocument();
  outDoc.Load(XmlReader.Create(mem));
  return outDoc;
}

当我尝试运行此代码时,收到XmlException“根元素丢失”。当我修改代码输出到测试文件时,我得到一个格式良好的Xml文档。任何人都可以告诉我为什么我能够输出到文件,但不能作为XmlDocument?

1 个答案:

答案 0 :(得分:6)

你没有倒回MemoryStream,你甚至不知道作者已经刷新了到流。我会有更多的东西:

using (MemoryStream mem = new MemoryStream()) {
    outSer.Serialize(mem, instance);
    mem.Position = 0;
    XmlDocument outDoc = new XmlDocument();
    outDoc.Load(mem);
    return outDoc;
}

实际上,我甚至可能会序列化为StringWriter;保存一些编码/解码开销:

string xml;
using (StringWriter writer = new StringWriter()) {
    outSer.Serialize(writer, instance);
    xml = writer.ToString();
}
XmlDocument outDoc = new XmlDocument();
outDoc.LoadXml(xml);
return outDoc;