开发者

XmlDocument.Load(xml) generates No Root Element error from XmlSerializer serialized code

I have a class like so:

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

    ...
    <snip>

    //end properties.
}

This class contains a static method to create an XmlDocument instance to pass to a BizTalk server. Like so:

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

GetMyMessageType creates an instance of MyMessageType, then calls the following code:

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;
}

When I attempt to run this code, I receive an XmlException "The Root Element is Missing." When I modify the code to output to a test file, I get a well-formed Xml document. Can any开发者_开发问答one tell me why I would be able to output to a file, but not as an XmlDocument?


You haven't rewound the MemoryStream, and you don't even know that the writer has flushed to the stream. I would have something more like:

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

Actually, I might even serialize to a StringWriter instead; save some encoding/decoding overhead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜