ismith
ismith

Reputation: 23

XDocument.Parse preserving whitespace when not asked to

I'm trying to load an XDocument from a string, which contains XML elements with excessive whitespace in their text nodes. From my understanding of the MSDN for the XDocument.Parse method, it's supposed to not preserve whitespace.

Why then, in this simple example, is whitespace still present?

string xml = "<doc> <node>this  should  be  collapsed</node> </doc>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc.Root.Element("node").Value);

The result of the Console.WriteLine call is the phrase with two spaces between each word. I expected only one space between each.

Upvotes: 2

Views: 3244

Answers (1)

Russ Ferri
Russ Ferri

Reputation: 6589

"Not preserving whitespace" means that any text nodes that contain only whitespace will be ignored while loading the XDocument.

Your xml string can be represented by the following tree:

 doc
 |--#text - " "
 |--node
 |  |--#text - "this  should  be  collapsed"
 |--#text - " "

If you inspect the contents of doc.Root.Value, you will see the string

"this  should  be  collapsed"

If you instead load the string while "preserving whitespace",

XDocument doc = XDocument.Parse(xml, LoadOptions.PreserveWhitespace);

and again inspect the contents of doc.Root.Value, you will see the string

" this  should  be  collapsed "

Upvotes: 2

Related Questions