Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some weird XML problem when trying to load into a string

Tags:

c#

xml

So basically long story short, I am losing a space from my xml file to c#

The xml file is generated by Libre Open Office (its a screen with text) and here is the text when displayed in Libre Open Office

your family's monthly

perfect, and HERE is the XML for that as displayed by Notepad++

<text:span text:style-name="T5">your family&apos;s</text:span><text:span text:style-name="T8"> </text:span><text:span text:style-name="T5">monthly </text:span>

Notice how there is a SPACE in the middle tag? That is good.

Now when I move into C# here is my code...

   XmlDocument doc = new XmlDocument();
   doc.Load(@"FILEPATH.xml");
   string xmlcontents = doc.InnerXml;

then when I inspect the contents of the string "xmlcontents" THIS is what I see

<text:span text:style-name="T2">your family's</text:span><text:span text:style-name="T3"></text:span><text:span text:style-name="T2">monthly </text:span>

This outputs "your family'smonthly" (not good !)

Notice how the space is GONE between "family's" and "monthly"? This screws me up down the road but if I were to edit the xml once loaded to manually put a space there (as seen in notepad++) it is fine.

Why is this happening?


1 Answers

This is caused by the PreserveWhitespace-Option being set to false by default.

The Load method always preserves significant white space. The PreserveWhitespace property determines whether or not insignificant white space, that is white space in element content, is preserved. The default is false; white space in element content is not preserved.

This should help:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(@"FILEPATH.xml");
string xmlcontents = doc.InnerXml;
like image 56
Christoph Sonntag Avatar answered Mar 26 '26 02:03

Christoph Sonntag