Home > Enterprise >  Backslashes "\" are added after converting XDocument to string using ToString method
Backslashes "\" are added after converting XDocument to string using ToString method

Time:05-02

After converting XDocument to string using .ToString(SaveOptions.DisableFormatting) method. Backslashes are added next to the double quotes in tag attributes.

Example of my XML construction using XDocument:

XNamespace xmlns = "http://www.w3.org/2001/10/synthesis";
            var xdec = new XDeclaration("1.0", "utf-8", "yes");
            XDocument xml = new XDocument(
                    xdec,
                    new XElement(
                        xmlns   "speak",
                        new XAttribute(XNamespace.Xml   "lang", "en")));

             var xmlString = xml.ToString(SaveOptions.DisableFormatting); // backslashes "\" are added

Output image example: enter image description here

How shall I remove these backslashes? Thanks.

CodePudding user response:

Backslashes are here to tell that double quotes are part of the string and do not indicate end of it. If you would have for example:

var myFavouriteQuoteStatement = "My favourite quote is "I like bread"";

Visual studio would mark this line with error because compiler would consider "My favourite quote is " as your string as myFavouriteQuoteStatement variable and the rest of it I like bread"" would be consider as garbage that cannot be compiled.

Valid string would be:

var myFavouriteQuoteStatement = "My favourite quote is \"I like bread\"";

You can event tell the difference by how Stackoverflow highlights it in may comment. It

  • Related