title: In C#, how do I convert a XmlNode to string, with indentation? (Without looping)
body: <p>This has got to be such a simple question but I just can't get the answer.</p>
  
  <p>I have an XmlNode and all I want to do is output this node, as a string, with  indentations (tabs or spaces) intact to provide better readability.</p>
  
  <p>So far I tried XmlWriter, XmlTextWriter, XmlDocument, XmlReader.</p>
  
  <ul>
  <li>I tried the PreserveWhitespace in XmlDocument but I couldn't get the XmlDocument to output my node.</li>
  <li>I tried the Formatting = Formatting.Indented property in XmlTextWriter but I couldn't figure out how to output the contents to string.</li>
  </ul>
  
  <p>To output the XmlNode as string WITHOUT indentation is easy. I just do XmlNode.OuterXml. How do I get the indentations in there? </p>
  
  <p>I want to do this without looping through the XmlNode and using brute force to add whitespace, because I think there should be a simpler way.</p>
  
  <p>Thanks.</p>
  
  <p>Edit: For future readers, here is the answer:</p>
  
  <pre><code>  var xmlNode = is some object of type XmlNode
  
    using (var sw = new StringWriter())
    {
        using (var xw = new XmlTextWriter(sw))
        {
          xw.Formatting = Formatting.Indented;
          xw.Indentation = 2; //default is 1. I used 2 to make the indents larger.
  
          xmlNode.WriteTo(xw);
        }
        return sw.ToString(); //The node, as a string, with indents!
    }
  </code></pre>
  
  <p>The reason I needed to do this was output the node's xml with syntax highlighting. I used AvalonEdit to highlight the xml, outputted the highlighted text to html, then converted the html to a FlowDocument which could be displayed in a RichTextBox.</p>