XmlNodeWriter Revisited

When answering posts on XML in the microsoft.public* newsgroups, I see a lot of questions on using XML without a file. I typically give an answer related to using the System.IO.MemoryStream and setting its .Position property to 0 to "rewind" the stream:

System.IO.MemoryStream mem = new System.IO.MemoryStream();
yourSerializer.Serialize(mem, yourObject);
mem.Position = 0;
XmlDocument doc = new XmlDocument();
doc.Load(mem);

However, Chris Lovett's response in a recent thread gave me pause for thought:

Or better still, use the XmlNodeWriter I published on https://www.gotdotnet.com and do the following:

XmlDocument doc = new XmlDocument();
yourSerializer.Serialize(new XmlNodeWriter(doc), yourObject)

and avoid the textifying and re-parsing of the XML strings.

For anyone that has not downloaded the XmlNodeWriter implementation Chris mentioned, I strongly urge you to do so. This bit of code helps shed some light on implementations of the XmlWriter class. The sample Chris included in the project is good, but the XmlNodeWriter is really cool when you use it to investigate other technologies like XSLT. Using the following bit of code, you can run an XSLT transform on a document and see the nodes as they are added to the result tree:

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://www.xmlandasp.net/links.xml");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "GET";
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse();
System.IO.Stream results = response.GetResponseStream();

XmlNodeWriter writer = new XmlNodeWriter(new XmlDocument());

System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(results);
System.Xml.Xsl.XslTransform trans = new XslTransform();
trans.Load(Server.MapPath("xsltfile1.xslt"));
trans.Transform(doc,null,writer);
writer.Close();

Very cool indeed.

<Kirk />