跟小D每日学口语

C#中用schema验证xml的合法性

class ValidateXML
    {
        public string ErrString = string.Empty;
        public void ValidationEventCallBack(Object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)//区分是警告还是错误 
            {
                //Console.WriteLine("验证成功!警告:" + e.Message);
                ErrString += "验证成功!警告:" + e.Message;
            }
            else
            {
               // Console.WriteLine("验证失败");
                ErrString += "Err:" + e.Message;
            }
        }

        public void CheckXmlValidate(string strRequestXML)
        {
            //string ErrString = string.Empty;
            StringReader sRead = null;
            XmlReader xmlRead = null;
            XmlSchemaSet schemaSet;

            try
            {
                schemaSet = new XmlSchemaSet();

                sRead = new StringReader(strRequestXML);

                schemaSet.Add(null, @"MySchema.xsd");

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventCallBack);
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas = schemaSet;

                xmlRead = XmlReader.Create(sRead, settings);
                while (xmlRead.Read())
                {

                }

                if (ErrString.ToString() == String.Empty)
                {

                    Console.WriteLine("验证成功!");
                }
                else
                {
                    Console.WriteLine("验证失败!原因可能是:" + ErrString);
                }
            }
            catch (XmlException exec)
            {
                Console.WriteLine(exec.Message);
            }
            finally
            {

                if (xmlRead != null)
                {

                    xmlRead.Close();
                }
            }
        }
    }

public static void Main(string[] args)
        {
ValidateXML vx = new ValidateXML();
            //StreamReader sr = new StreamReader(new FileStream(@"test.xml", FileMode.Open));
            vx.CheckXmlValidate(File.ReadAllText(@"test.xml"));

            PressQtoQuit();
        }

public static void PressQtoQuit()
        {
            Console.WriteLine("Hit Q to exit");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey().Key;
            } while (key != ConsoleKey.Q);
        }

Reference from : https://msdn.microsoft.com/en-us/library/as3tta56(v=vs.80).aspx

Reference from : http://www.cnblogs.com/joean/p/4982875.html

posted @ 2017-09-19 16:05  Danny Chen  阅读(598)  评论(0编辑  收藏  举报