Xml Validation Tool in VS

Xml Validation Tool in VS
 
VS is a good tool for editing xml. However, I often need to validate whether the whole xml is in good format. IE can do this validation for us. If the xml is in wrong format, the IE will report error. But IE requires that the file is with xml extension. It’s a little bit inconvenient, because sometimes, the file is not with xml extension although it’s really in xml format, such as *.manifest file. So I just wrote a simple tool to validate the whole xml document is in correct format. Of course, I don’t take account of xslt format validation. It just does the basic validation.
Create a brand new C# console project, add reference to System.Windows.Form component, and add the code like below:
using System;
using System.Collections.Generic;
using System.Text;
 
//Added by Simon
using System.Xml;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
 
namespace SimonXmlValidator
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                string exeName = Process.GetCurrentProcess().MainModule.ModuleName;
                string str = "The argument is missing. \nUsage:" + exeName + " XmlFilePath";
                Console.WriteLine(str);
                MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            string xmlFilePath = args[0];
            if (!File.Exists(xmlFilePath))
            {
                string str = "The xml file doesn't exist. \n" + xmlFilePath;
                Console.WriteLine(str);
                MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);               
                return;
            }
 
            XmlDocument xmlDoc = new XmlDocument();
 
            try
            {
                xmlDoc.Load(xmlFilePath);
                Console.WriteLine("Good");
                MessageBox.Show("Good", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);              
 
                return;
            }
            catch (System.Exception e)
            {
                string str = e.Message;
                Console.WriteLine(str);
                MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }
}
Build the C# project, and get the exe. Go to VS->Tools->External Tools, and add the exe as an external tool. Note: Set $(ItemPath) as the arguments. After 「OK」, a new menu item will be added in the tools menu.
Then after editing an xml file, save it, click the menu item, you can validate whether the xml doc is in good format or not.
相關文章
相關標籤/搜索