Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 769
user40907 Avatar asked Nov 12 '10 04:11

user40907


2 Answers

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
    }; 
like image 96
Almund Avatar answered Sep 23 '22 06:09

Almund


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.

like image 30
user40907 Avatar answered Sep 23 '22 06:09

user40907