C#或javascript代码格式化程序

时间:2010-02-26 13:28:12

标签: c# asp.net javascript syntax-highlighting code-formatting

我目前正在使用Syntax Highlighter在页面上显示XML或SOAP消息。这适用于已经正确格式化的消息(换行符,缩进等)。但是,如果我有一个XML字符串,如:

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

我会将字符串写入页面,而javascript highlighter会正确地语法突出显示字符串,但它会全部在一行上。

是否有C#字符串格式化程序或某些语法高亮库,它具有“智能”缩进功能,可以插入换行符,缩进等...?

1 个答案:

答案 0 :(得分:2)

由于这是一个字符串,添加换行符和缩进将改变变量xml的实际,这是你想要的代码格式化器要做!

请注意,您可以在写入页面之前在C#中格式化XML,如下所示:

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