如何使用XSD2 code生成的C#类 [英] How to use XSD2CODE generated C# classes

查看:217
本文介绍了如何使用XSD2 code生成的C#类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的XSD的世界里,我曾与XML,但没有太大的programtically。 使用XSD2 code.Can有人请指引我,我该如何使用这些生成的类使用C#,用我的XML得到验证我已经成功地生成的C#类。

I am new to XSD world, I worked with XML but not much programtically. I have successfully generated C# classes using XSD2Code.Can somebody please guide me how can I use those generated classes using C# and use my XML to get validated.

code段将hightly AP preciated。

Code snippet would be hightly appreciated.

感谢和问候。

推荐答案

验证XML并不需要有生成的类。让我们看看这个辅助类:

Validating an XML does not need to have the generated classes. Lets see this helper class:

public class Validator
    {
        XmlSchemaSet schemaset;
        ILog logger;
        static Validator instance;
        static object lockObject = new Object();

        public static Validator Instance
        {
            get { return instance; }
        }

        public Validator(string schemaPath)
        {
            WarningAsErrors = true;
            logger = LogManager.GetLogger(GetType().Name);
            schemaset = new XmlSchemaSet();
            foreach (string s in Directory.GetFiles(schemaPath, "*.xsd"))
            {
                schemaset.Add(XmlSchema.Read(XmlReader.Create(s),new ValidationEventHandler((ss,e)=>OnValidateReadSchema(ss,e))));
            }
            instance = this;
        }

        private void OnValidateReadSchema(object ss, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error)
                logger.Error(e.Message);
            else
                logger.Warn(e.Message);
        }
        public bool WarningAsErrors { get; set; }
        private string FormatLineInfo(XmlSchemaException xmlSchemaException)
        {
            return string.Format(" Line:{0} Position:{1}", xmlSchemaException.LineNumber, xmlSchemaException.LinePosition);
        }
        protected void OnValidate(object _, ValidationEventArgs vae)
        {
            if (vae.Severity == XmlSeverityType.Error)
                logger.Error(vae.Message);
            else
                logger.Warn(vae.Message);
            if (vae.Severity == XmlSeverityType.Error || WarningAsErrors)
                errors.AppendLine(vae.Message + FormatLineInfo(vae.Exception));
            else
                warnings.AppendLine(vae.Message + FormatLineInfo(vae.Exception));
        }

        public string ErrorMessage { get; set; }
        public string WarningMessage { get; set; }
        StringBuilder errors, warnings;
        public void Validate(String doc)
        {
            lock (lockObject)
            {
                errors = new StringBuilder();
                warnings = new StringBuilder();

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.CloseInput = true;
                settings.ValidationEventHandler += new ValidationEventHandler((o, e) => OnValidate(o, e));  // Your callback...
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas.Add(schemaset);
                settings.ValidationFlags =
                  XmlSchemaValidationFlags.ReportValidationWarnings |
                  XmlSchemaValidationFlags.ProcessIdentityConstraints |
                  XmlSchemaValidationFlags.ProcessInlineSchema |
                  XmlSchemaValidationFlags.ProcessSchemaLocation;

                // Wrap document in an XmlNodeReader and run validation on top of that
                try
                {
                    using (XmlReader validatingReader = XmlReader.Create(new StringReader(doc), settings))
                    {
                        while (validatingReader.Read()) { /* just loop through document */ }
                    }
                }
                catch (XmlException e)
                {
                    errors.AppendLine(string.Format("Error at line:{0} Posizione:{1}", e.LineNumber, e.LinePosition));
                }
                ErrorMessage = errors.ToString();
                WarningMessage = warnings.ToString();
            }
        }

    }

为了使用它,只是创建验证的实例,通过在您的XSD保持的路径。然后调用验证(串)传递XML文档的内容。你会发现设置了错误的的ErrorMessage WarningMessage 属性/警告发现(如果有)。为了工作,XML文档必须有正确的(S)的xmlns 声明。请注意我的类使用log4net的默认情况下为记录机制,所以它不会编译成是,除非你正在使用log4net的了。

In order to use it, just create an instance of Validator, passing the path where your xsd stays. Then call Validate(string) passing the XML document content. You will find the ErrorMessage and WarningMessage properties set up with the errors/warning found ( if one ). In order to work, the XML document has to have the proper(s) xmlns declared. Notice my class uses log4net by default as a logger mechanism, so it will not compile as is unless you are using log4net too.

这篇关于如何使用XSD2 code生成的C#类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆