title: How to create a XmlDocument using XmlWriter in .NET?
body: <p>Many .NET functions use XmlWriter to output/generate xml. Outputting to a file/string/memory is a very operation:</p>
  
  <pre><code>XmlWriter xw = XmlWriter.Create(PutYourStreamFileWriterEtcHere);
  xw.WriteStartElement("root");
  ...
  </code></pre>
  
  <p>Sometimes , you need to manipulate the resulting Xml and would therefore like to load it into a XmlDocument or might need an XmlDocument for some other reason but you must generate the XML using an XmlWriter. For example, if you call a function in a 3rd party library that outputs to a XmlWriter only.</p>
  
  <p>One of the things you can do is write the xml to a string and then load it into your XmlDocument:</p>
  
  <pre><code>StringWriter S = new StringWriter();
  XmlWriter xw = XmlWriter.Create(S);
  /* write away */
  XmlDocument xdoc = new XmlDocument();
  xdoc.LoadXml(S.ToString());
  </code></pre>
  
  <p>However this is inefficient - first you serialize all the xml info into a string, then you parse the string again to create the DOM.</p>
  
  <p>How can you point an XmlWriter to build a XmlDocument directly?</p>