Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  aaaa
Language: C/C++
Code:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
 
namespace HtmlIndexGenerator
{
    class Program
    {
        const string HeaderPattern = @"<h(?<level>[1-6])[\s\S]*?>[\s\S]*?</h([1-6])>";
        const string TagPattern = @"<[\s\S]*?>";
        const string IdPattern = "(id|name)=\"(?<id>[\\s\\S]*?)\"";
 
        const int MaxHeaderLimit = 6;
 
        const string H1Style = @"font-weight:bold";
        const string H2Style = @"";
        const string H3Style = @"";
        const string H4Style = @"";
        const string H5Style = @"";
        const string H6Style = @"font-size:10px;";
 
        static string[] HeaderStyles = new string[]{
            H1Style,
            H2Style,
            H3Style,
            H4Style,
            H5Style,
            H6Style
        };
 
        static void Main(string[] args)
        {
            string fileName;
            int limit;
            ParseParameter(args, out fileName, out limit);
 
            string html = GetHtml(fileName);
 
            if (string.IsNullOrEmpty(html))
                return;
 
            string index = GenerateIndex(html, limit);
 
            string outputFile = "index.htm";
            File.WriteAllText(outputFile, index, Encoding.UTF8);
            Console.WriteLine("{0} generated.", outputFile);
        }
 
        /// <summary>
        /// Prints help document.
        /// </summary>
        private static void PrintHelp()
        {
            Console.WriteLine("Usage: IndexGen.exe [filename] [-l] level");
            Console.WriteLine("-l: header level limit, -l 3 limit the output to <h3>");
            Console.WriteLine("Example: IndexGen.exe page.htm");
        }
 
        /// <summary>
        /// Parses command line paramters.
        /// </summary>
        /// <param name="args">Input parameters</param>
        /// <param name="fileName">Output parameter for parsed file name. Null if parse failed.</param>
        /// <param name="limit">Output parameter for header level limit.</param>
        private static void ParseParameter(string[] args, out string fileName, out int limit)
        {
            fileName = null;
            limit = MaxHeaderLimit;
 
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Equals("-l", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (i + 1 >= args.Length || !int.TryParse(args[i + 1], out limit))
                    {
                        Console.WriteLine("Invalid parameter for -l");
                        PrintHelp();
                        return;
                    }
                }
            }
            if (args.Length > 0)
            {
                fileName = args[args.Length - 1];
            }
        }
 
        /// <summary>
        /// Reads html content according to specified file name.
        /// </summary>
        /// <param name="fileName">File name</param>
        /// <returns>Html content of the specific file.</returns>
        private static string GetHtml(string fileName)
        {
            string html = null;
            if (string.IsNullOrEmpty(fileName))
            {
                Console.WriteLine("Specify a file name");
                PrintHelp();
                return html;
            }
            if (!File.Exists(fileName))
            {
                Console.WriteLine("File {0} dose not exist", fileName);
                PrintHelp();
                return html;
            }
 
            // Auto defect file encoding.
            using (StreamReader reader = new StreamReader(fileName, detectEncodingFromByteOrderMarks: true))
            {
                Encoding encoding = reader.CurrentEncoding;
                html = File.ReadAllText(fileName, encoding);
            }
            return html;
        }
 
        /// <summary>
        /// Generates the index html.
        /// </summary>
        /// <param name="html">Html content of specified file.</param>
        /// <param name="limit">Header limit</param>
        /// <returns>Generated index html</returns>
        private static string GenerateIndex(string html, int limit)
        {
            Regex regex = new Regex(HeaderPattern, RegexOptions.IgnoreCase);
            Regex regexId = new Regex(IdPattern, RegexOptions.IgnoreCase);
            MatchCollection headerMatches = regex.Matches(html);
 
            int previousLevel = 1;
 
            StringBuilder indexBuilder = new StringBuilder();
            indexBuilder.Append("<div id=\"doc-index\">");
            indexBuilder.Append("<ul>");
            foreach (Match headerMatch in headerMatches)
            {
                int currentLevel = int.Parse(headerMatch.Groups["level"].Value);
                string header = Regex.Replace(headerMatch.Value, TagPattern, string.Empty);
 
                Match idMatch = regexId.Match(headerMatch.Value);
                string id = idMatch.Success ? idMatch.Groups["id"].Value : null;
 
                string link = string.IsNullOrEmpty(id) ? header : string.Format("<a href=\"#{0}\">{1}</a>", id, header);
 
                if (currentLevel == previousLevel)
                {
                    indexBuilder.AppendFormat("<li style=\"{1}\">{0}</li>", link, HeaderStyles[currentLevel - 1]);
                }
                else if (currentLevel > previousLevel && currentLevel <= limit)
                {
                    indexBuilder.AppendFormat("<ul><li style=\"{1}\">{0}</li>", link, HeaderStyles[currentLevel - 1]);
                    previousLevel = currentLevel;
                }
                else if (currentLevel < previousLevel)
                {
                    indexBuilder.AppendFormat("</ul><li style=\"{1}\">{0}</li>", link, HeaderStyles[currentLevel - 1]);
                    previousLevel = currentLevel;
                }
            }
            indexBuilder.Append("</ul></div>");
            return indexBuilder.ToString();
        }
    }
}
Comments: