title: How to write an XElement to an XmlWriter that has contents already
body: <p>Im am trying to write a very large XML document in a streaming manner. Instead of writing one <code>XDocument</code> or <code>XElement</code>, which might consume too much memory, the idea is that I write the root element using an <code>XmlWriter</code>, and then write many XElements to that writer, one after the other, before closing the root element. However, I have not found a way to do so. To simulate the problem, consider the following code:</p>
  
  <pre><code>using System;
  using System.Xml;
  using System.Xml.Linq;
  
  internal static class Program
  {
      private static void Main()
      {
          var settings = new XmlWriterSettings { Encoding = Console.OutputEncoding, Indent = true };
  
          using (var writer = XmlWriter.Create(Console.Out, settings))
          {
              const string namespaceUri = "http://example.com/";
  
              writer.WriteStartElement("x", "root", namespaceUri);
  
              XNamespace x = namespaceUri;
  
              XElement element = new XElement(x + "test");
  
              element.Save(writer);
  
              writer.WriteEndElement();
          }
  
          Console.WriteLine();
      }
  }
  </code></pre>
  
  <p>The program fails on the <code>element.Save(writer);</code> line, with an <code>InvalidOperationException</code>: "Token StartDocument in state Element Start Tag would result in an invalid XML document".</p>
  
  <p>The reason for this exception is clear: the XElement is assuming it has the entire XmlWriter all for itself, and calls <code>WriteStartDocument()</code> on it. Obviously that fails, as the document was already started, and already has a start element in it.</p>
  
  <p>Note that I would expect this behavior if I were to use <code>XDocument</code>, but I'm not, I'm using <code>XElement</code>.</p>
  
  <p>An alternative would be to write</p>
  
  <pre><code>            writer.WriteRaw(element.ToString());
  </code></pre>
  
  <p>instead of </p>
  
  <pre><code>            element.Save(writer);
  </code></pre>
  
  <p>It works, in the sense that it doesn't crash, and in the sense that it produces correct XML.</p>
  
  <p>However, I don't like it, because it doesn't produce the clean and efficient XML I am looking for (it needlessly repeats the namespace declarations). It obviously couldn't, as the XElement is serialized without the context that the XmlWriter should provide. The fact that it needs an intermediary string to work is not even the biggest problem.</p>
  
  <p>How should I write many <code>XElement</code> instances independently, one after the other, to an <code>XmlWriter</code>, in an efficient way, so that clean XML is produced? Or is this not possible?</p>