使用XSD实现对XML文件的验证

    技术2022-05-11  77

    贴代码先: using  System; using  System.Collections.Generic; using  System.Text; using  System.Xml; using  System.Xml.Schema; using  System.IO; namespace  XmlChecker {    class Program    {        static void Main(string[] args)        {            if (args.Length != 2)            {                Console.WriteLine("usage: XmlChecker.exe xmlfile xsdfile");                return;            }            if (!File.Exists(args[0]))            {                Console.WriteLine("xml file not exists!");                return;            }            if (!File.Exists(args[1]))            {                Console.WriteLine("xsd file not exists!");                return;            }            XmlReaderSettings xsd = new XmlReaderSettings();            xsd.ValidationType = ValidationType.Schema;            xsd.Schemas.Add("", args[1]);            xsd.ValidationEventHandler += new ValidationEventHandler(xsd_ValidationEventHandler);            XmlReader xml = XmlReader.Create(args[0], xsd);            while (xml.Read())            {            }            xml.Close();            xml = null;            Console.WriteLine("Check Complete!");        }        private static void xsd_ValidationEventHandler(object sender, ValidationEventArgs e)        {            Console.WriteLine(e.Severity.ToString() + " " + e.Message +                 "(" + e.Exception.LineNumber + "" + (e.Exception.LinePosition/2+ ")");        }    }}     在参数中指定XML文件和XSD文件的位置,就能够显示出XML文件中不符合架构的地方。     奇怪的是,VS2005中居然没有内置XML文件验证的功能,也有可能是我没发现。请发现了的朋友告诉我,谢谢!

    最新回复(0)