title: Remove Insignificant Whitespace From Xml Document
body: <p>I've got an xml file that contains both significant and insignificant whitespace. I would like to read this file in and write the file back out to disk, removing insignificant whitespace. When considering significant vs insignificant whitespace, I want to make sure that spaces within mixed content elements (as defined by my schema) are maintained. How can I do this using C#?</p>
  
  <p>Based on <a href="http://msdn.microsoft.com/en-us/library/6f00zs65%28v=vs.100%29.aspx" rel="nofollow">this article</a> that I read, it sounded like I might need to use a validating xml reader so that the reader would know which elements contain mixed content per the schema. Below is one example of some code I tried that did not maintain significant whitespace between elements within a parent element containing mixed content.</p>
  
  <pre><code>XmlDocument doc = new XmlDocument();
  doc.PreserveWhitespace = true;
  using (XmlTextReader rdr = new XmlTextReader(xmlFilePath1))
  {
      rdr.WhitespaceHandling = WhitespaceHandling.Significant;
      XmlSchemaSet sc = new XmlSchemaSet();
      sc.Add(null, @"C:\my-schema.xsd");
      doc.Load(XmlReader.Create(rdr, new XmlReaderSettings() { ValidationType = System.Xml.ValidationType.Schema, Schemas = sc }));
      using (XmlTextWriter writer = new XmlTextWriter(xmlFilePath2, Encoding.UTF8))
      {
          writer.Formatting = Formatting.None;
          doc.Save(writer);
      }
  }
  </code></pre>
  
  <p>Below is an example of xml where I would like to maintain whitespace. I am expecting the whitespace between the two inline tag elements to be maintained. Para is defined in the schema as having mixed content.</p>
  
  <pre><code>&lt;para&gt;i have a bunch of text here with some &lt;inlinetag attrib="a"/&gt; &lt;inlinetag attrib="b"/&gt;&lt;/para&gt;
  </code></pre>
  
  <p>Here is a simple example of whitespace that I would want to remove. In this example, the markup came from a printy printed xml document with tabs or spaces in front of elements and line breaks after them. I would want to keep the whitespace inside the para but not outside of it.</p>
  
  <pre><code>  &lt;entry colname="col2"&gt;
      &lt;para&gt;Lorem ipsum dolor sit amet, et nulla diam.&lt;inlineTag value="a"/&gt; &lt;inlineTag value="b"/&gt;&lt;/para&gt;
    &lt;/entry&gt;
  </code></pre>