C # LINQ to XML missing space character

I write the XML file "manually" (ie not with LINQ to XML), which sometimes includes an open / close tag containing one whitespace character. When viewing the resulting file, everything looks correct, example below ...

<Item> <ItemNumber>3</ItemNumber> <English> </English> <Translation>Ignore this one. Do not remove.</Translation> </Item> 

... the reasons for this are different and irrelevant, this is being done.

Later, I use the C # program with LINQ to XML to read the file and extract the record ...

 XElement X_EnglishE = null; // This is CRAZY foreach (XElement i in Records) { X_EnglishE = i.Element("English"); // There is only one damned record! } string X_English = X_EnglishE.ToString(); 

... and check that it does not change from the database record. I detect a change in processing elements in which the field has a single space ...

 +E+ Text[3] English source has been altered: Was: >>> <<< Now: >>><<< 

... β†’> and <the parts that I added to see what happens (it's hard to see the space characters). I was busy with this, but I don’t understand why this is so. This is not entirely important as the field is not used (yet), but I cannot trust C # or LINQ or what does this if I do not understand why this is so. So what does this do and why?

+4
source share
3 answers

You need to keep spaces when loading the XML string:

 XDocument doc = XDocument.Parse(@" <Item> <ItemNumber>3</ItemNumber> <English> </English> <Translation>Ignore this one. Do not remove.</Translation> </Item>", LoadOptions.PreserveWhitespace); string X_English = (string)doc.Root.Element("English"); // X_English == " " 
+2
source

It looks the same as the behavior you get in HTML, where leading / trailing spaces are stacked into themselves, which leads to an empty pool. I think that if you put one space in a CDATA block, this may solve it.

+2
source

In spaces, XML (like space) is ignored after and before tags. The parsed XML ignores this single space because it is perceived as formatting (since there is no text around it) and therefore it does not appear in your output.

+2
source

Source: https://habr.com/ru/post/1308358/


All Articles