Preserving White Space while Loading or Parsing XML
This topic describes how to control the white space behavior of LINQ to XML.
A common scenario is to read indented XML, create an in-memory XML tree without any white space text nodes (that is, not preserving white space), perform some operations on the XML, and then save the XML with indentation. When you serialize the XML with formatting, only significant white space in the XML tree is preserved. This is the default behavior for LINQ to XML.
Another common scenario is to read and modify XML that has already been intentionally indented. You might not want to change this indentation in any way. To do this in LINQ to XML, you preserve white space when you load or parse the XML and disable formatting when you serialize the XML.
This topic describes the white space behavior of methods that populate XML trees. For information about controlling white space when you serialize XML trees, see Preserving White Space While Serializing.
If the method does not take LoadOptions as an argument, the method will not preserve insignificant white space.
In most cases, if the method takes LoadOptions as an argument, you can optionally preserve insignificant white space as text nodes in the XML tree. However, if the method is loading the XML from an XmlReader, then the XmlReader determines whether white space will be preserved or not. Setting PreserveWhitespace will have no effect.
With these methods, if white space is preserved, insignificant white space is inserted into the XML tree as XText nodes. If white space is not preserved, text nodes are not inserted.
You can create an XML tree by using an XmlWriter. Nodes that are written to the XmlWriter are populated in the tree. However, when you build an XML tree using this method, all nodes are preserved, regardless of whether the node is white space or not, or whether the white space is significant or not.