nivlam
nivlam

Reputation: 3253

C# or javascript code formatter

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... ?

Upvotes: 4

Views: 1622

Answers (1)

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171559

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();
        }
    }
}

Upvotes: 2

Related Questions