title: Save XDocument with indentation and xml:space="preserve"
body: <p>I want to pretty print an <a href="https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx" rel="noreferrer">XDocument</a> but leaving white space inside <code>xml:space="preserve"</code> elements untouched.</p>
  
  <p>This snippet:</p>
  
  <pre><code>new XDocument(
      new XElement("a",
          new XElement("b",
              new XElement("c"))))
      .Save(Console.Out);
  </code></pre>
  
  <p>Results in the following indented output (which is just want I want):</p>
  
  <pre><code>&lt;a&gt;
    &lt;b&gt;
      &lt;c /&gt;
    &lt;/b&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>However, let's say that I need to preserve white space inside the <code>&lt;b&gt;</code> element:</p>
  
  <pre><code>new XDocument(
      new XElement("a",
          new XElement("b",
              new XAttribute(XNamespace.Xml + "space", "preserve"),
              new XElement("c"))))
      .Save(Console.Out);
  </code></pre>
  
  <p>In this case I get the following output:</p>
  
  <pre><code>&lt;a&gt;
    &lt;b xml:space="preserve"&gt;
      &lt;c /&gt;
    &lt;/b&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>This is not good, since indentation was added <em>inside</em> the <code>xml:space="preserve"</code> scope. The expected output in this case would be:</p>
  
  <pre><code>&lt;a&gt;
    &lt;b xml:space="preserve"&gt;&lt;c /&gt;&lt;/b&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>I'm surprised that <a href="https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx" rel="noreferrer">XDocument</a> doesn't support this by default.</p>
  
  <p>Is it possible to get a pretty printed (indented) output from an <a href="https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx" rel="noreferrer">XDocument</a> <strong>and keeping white space inside <code>xml:space="preserve"</code> as-is</strong>?</p>
  
  <p>I understand that one option is to write my own <a href="https://msdn.microsoft.com/en-us/library/system.xml.xmlwriter(v=vs.110).aspx" rel="noreferrer">XmlWriter</a> implementation that takes care of this, but I would rather use something from the framework (if available).</p>