Thursday, May 17, 2007

Get XmlDocument from a class

So - I've been trying to find an easy way to add a ToXml() method to a lot of objects lately. Here's what I've come up with:

MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms);
XmlSerializer xs = new XmlSerializer(this.GetType());
xs.Serialize(writer, this);
XmlDocument doc = new XmlDocument();

// Need to start at the beginning of the MemoryStream
ms.Seek(0, SeekOrigin.Begin);

return doc;

The Seek method took me the longest to figure out. I kept getting a "Root node is missing." exception.

Hope this helps someone.

No comments: