开发者

C# or javascript code formatter

I'm currently using Syntax Highlight开发者_运维知识库er 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... ?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜