Thursday, November 4, 2010

XmlTidy

Needed a tool to tidy some Xml in "Programmer's Notepad" and could not resist to created my own version of XmlTidy. :-)

using System;
using System.Xml;
using System.Xml.XPath;

namespace XmlTidy
{
    public class Program
    {
        private enum ExitCodes
        {
            Success = 0,
            Failure = 1
        }

        private static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                return ShowUsage();
            }

            var inputFile = args[0];
            var outputFile = args.Length == 1 ? args[0] : args[1];
            return Tidy(inputFile, outputFile);
        }

        private static int ShowUsage()
        {
            Console.WriteLine("Usage: XmlTidy <inputfile> <outputfile>");
            Console.WriteLine("if <outputfile> is not specified, the <inputfile> is overwritten.");
            return (int)ExitCodes.Success;
        }

        private static int Tidy(string inputFile, string outputFile)
        {
            var result = (int)ExitCodes.Success;
            try
            {
                var document = new XPathDocument(inputFile);
                var settings = new XmlWriterSettings { IndentChars = "\t", Indent = true };
                var writer = XmlWriter.Create(outputFile, settings);
                document.CreateNavigator().WriteSubtree(writer);
                writer.Close();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                result = (int)ExitCodes.Failure;
            }

            return result;
        }
    }
}

Share:

0 kommentarer:

Post a Comment