Search code examples
c#xmllinq-to-xmlcarriage-returnlinefeed

Preserving special chars in xml


I've an xml string stored in the db table with line feed characters. In my C# 3.5 program, I load and manipulate it using Linq to xml and then show it as a string in the textbox control on the UI form.

I need to indent this xml as well as preserve line feeds/carriage return while showing it in the UI.

Am able to indent it but how do I preserve LF/CR chars in the xml??

Here's the sample C# code:

    XElement rootNode = CreateRootNode();
    XElement testXmlNode = XElement.Parse(xmlFromDbWithLFChars);

    rootNode.Add(testXmlNode );

    var builder = new StringBuilder();
    var settings = new XmlWriterSettings()
    {
     Indent = true
    };

    using (var writer = XmlWriter.Create(builder, settings))
    {
     rootNode.WriteTo(writer);
    }
    xmlString  = builder.ToString();   

    xmlString = xmlString.Replace("
", Environment.NewLine); //Doesnt work

    xmlString = xmlString.Replace("
", Environment.NewLine);  //Doesnt work

//Heres how the xml should look like in the UI control:
 <TestNode
             name="xyz"
             Id="12">
             <Children>
                  <Child name="abc" location="p" />
             </Children>
    </TestNode>

Solution

  • What you want to do is to set the settings of formatting on the XmlWriter, so change your row:

    var settings = new XmlWriterSettings() 
        { 
         Indent = true 
        }; 
    

    To something like this:

    var settings = new XmlWriterSettings() 
        { 
         Indent = true,
         IndentChars = "\n",
         NewLineOnAttributes = true
        };