views:

203

answers:

1

I'm currently using Syntax Highlighter to show a XML or SOAP messages on a page. That works fine for messages that are already formatted correctly (line breaks, indents, etc). But if I had a XML string like:

string xml = "<doc><object><first>Joe</first><last>Smith</last></object></doc>";

I would write the string to the page and the javascript highlighter would correctly syntax highlight the string, but it would be all on a single line.

Is there a C# string formatter or some syntax highlighting library that has a "smart" indent feature that would insert line breaks, indents, etc... ?

+1  A: 

Since this is a string, adding line breaks and indents would be changing the actual value of variable xml, which is not what you want your code formatter to do!

Note that you can format the XML in C# before writing to the page, like this:

using System;
using System.IO;
using System.Text;
using System.Xml;

namespace XmlIndent
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = "<doc><object><first>Joe</first><last>Smith</last></object></doc>";
            var xd = new XmlDocument();
            xd.LoadXml(xml);
            Console.WriteLine(FormatXml(xd));
            Console.ReadKey();
        }


        static string FormatXml(XmlDocument doc)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);
            XmlTextWriter xtw = null;
            using(xtw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
            {
                doc.WriteTo(xtw);
            }
            return sb.ToString();
        }
    }
}
RedFilter
The Visual Studio code formatter (Ctrl + K, D) formats your document by adding indents and line breaks. Same thing isn't it?
nivlam
No, you'll notice it will not format `string xml = "<doc><object><first>Joe</first><last>Smith</last></object></doc>";` as if it were XML, for the reasons stated in my answer.
RedFilter
I meant that it would format your document. You mentioned that changing the variable would be a bad thing. I was comparing that to changing a "code file".
nivlam
I am not saying formatting code is bad, I am saying there is a fundamental difference between code and data. Formatting code in C# does not change its meaning. Formatting data or values, such as a string assigned to a variable, **can** change its meaning, which is why `Ctrl + K, D` will not touch it. Two completely different domains. There is nothing wrong with your desire to format the XML, but any tool that will blindly automate this for you is very dangerous, as it is not differentiating between the two domains. This formatting should only be done explicitly by the developer when needed.
RedFilter