开发者

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.


"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 "
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜