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>
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
    }; 
Thanks all for your responses. Finally,I could get this working.
My approach does not use Linq2Xml/SAX parser.Am generating the xml using StringBuilder and showing it in the UI in a winforms Rich textbox control.Now,I can see line-feeds as it is in the UI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With