How to save space characters when parsing XML from C # LINQ

What do I need to do either in my C # code or in my XML document so that the XDocument parser reads literal spaces for Value from XElement s?


Background

I have an XML document, part of which is as follows:

  <NewLineString>&#10;&#13;</NewLineString> <IndentString> </IndentString> 

I add the values โ€‹โ€‹of each XElement to the data dictionary using the LINQ query; The .ForEach part is as follows:

  .ForEach(x => SchemaDictionary.Add( LogicHelper.GetEnumValue(x.Name.ToString()), x.Value)); 

To check if spaces are saved, I print a string of character numbers for each value item in the data dictionary. In the following code, x represents a KeyValuePair , and Aggregate just creates a string of integer character values:

 x.Value.ToCharArray() .Aggregate<char,string>("",(word,c) => word + ((int)c).ToString() + " " ) )); 

I expected to see 10 13 for the value of <NewLineString> and 32 32 32 32 for the value of <IndentString> . However, nothing was printed for each value (note: other XML escape values, such as &lt; correctly printed their character numbers).

What do I need to do either in C # code or in my XML document so that my parser adds a full space string to the data dictionary?

+6
c # xml linq whitespace
source share
3 answers

Try loading XDocument with LoadOptions.PreserveWhitespace

+7
source share

Try loading the document this way.

 XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("book.xml"); 
+1
source share

or just change your xml input to:

 <NewLineString>&#10;&#13;</NewLineString> <IndentString xml:space="preserve"> </IndentString> 
-3
source share

All Articles