XmlNodeWriter is an implementation of XmlWriter that is created with reference to an XmlDocument allowing the creation of an XmlDocument from code that expects a writer object. XmlNodeWriter was available as sample code via MSDN.
We had used this class and another memory buffer based mechanisms for generating XmlDocument's. It turns out that the framework does have its own mechanism for creating an XmlWriter for writing to an XmlDocument, via the XPathNavigator object created from the XmlDocument. The following code snippets demonstrate how this can be used.
The following code snippet shows how some of our code used a memory buffer for creating a dom via an XmlWriter, this is pretty inefficient and introduced bugs as shown below where the encoding was provided which couldn't handle non Unicode characters very well, replacing them with '?', and blew up with “” characters. It works better when you don't specify the encoding but its still inefficient, although I haven't tested if it still works with “” characters.
MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter( ms, Encoding.Default );
obj.WriteXml( writer );
// Load into a dom and return
writer.Flush();
ms.Position = 0;
XmlDocument dom = new XmlDocument();
dom.Load( ms );
return dom;
The implementation using the XmlNodeWriter sample code looks like:
XmlDocument doc = new XmlDocument();
obj.WriteXml(new XmlNodeWriter(doc, false));
The implementation using only framework classes is:
XmlDocument dom = new XmlDocument();
using (XmlWriter writer = dom.CreateNavigator().AppendChild())
{
obj.WriteXml(writer);
}
It can also be used when your performing an XSLT:
XmlDocument outputDom = new XmlDocument();
using (XmlWriter writer = outputDom.CreateNavigator().AppendChild())
{
XslCompiledTransform ct = new XslCompiledTransform();
ct.Load(stylesheetUri);
ct.Transform(inputDom, args, writer);
}