4

I have following XElement:

<title>
  <bold>Foo</bold>
  <italic>Bar</italic>
</title>

When I get Value property it returns FooBar without space. How to fix it?

Poma
  • 8,174
  • 18
  • 82
  • 144

2 Answers2

8

By definition, the Value of the <title> element is the concatenation of all text in this element. By default whitespace between elements and their contents is ignored, so it gives "FooBar". You can specify that you want to preserve whitespace:

var element = XElement.Parse(xml, LoadOptions.PreserveWhitespace);

However it will preserve all whitespace, including the line feeds and indentation. In your XML, there is a line feed and two spaces between "Foo" and "Bar"; how is it supposed to guess that you only want to keep one space?

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • In my case it preserves only one space (and one in the end, just like html). Don't know why but that's exactly what I need. – Poma Sep 22 '11 at 14:41
0

From the documentation for the Value property of the XElement class:

Gets or sets the concatenated text contents of this element.

Given your example, this behavior is expected. If you want spaces, you will have to provide the logic to do it.

casperOne
  • 73,706
  • 19
  • 184
  • 253