如何使用XSD2CODE生成的C#类

时间:2011-06-23 08:50:09

标签: c# .net xml xsd xsd2code

我是XSD世界的新手,我使用XML但没有太多的程序。 我已经使用XSD2Code成功生成了C#类。有人请指导我如何使用C#生成这些类并使用我的XML进行验证。

代码片段会很受欢迎。

谢谢和问候。

2 个答案:

答案 0 :(得分:1)

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

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();
            }
        }

    }

为了使用它,只需创建Validator的实例,传递xsd所在的路径。然后调用Validate(string)传递XML文档内容。您会发现ErrorMessageWarningMessage属性设置了错误/警告(如果有)。为了工作,XML文档必须声明正确的xmlns。请注意,我的类默认使用log4net作为记录器机制,因此除非您也使用log4net,否则它不会按原样编译。

答案 1 :(得分:0)

查看生成的Xsd2Code的Serialize和Deserialize方法,它看起来不像是模式验证。我没有太多使用Xsd2Code,所以我可能错了。

但你可以做的是使用XmlReaderSettings类来设置XML将使用的模式。

// Load the Schema Into Memory. The Error handler is also presented here.
StringReader sr = new StringReader(File.ReadAllText("schemafile.xsd"));
XmlSchema sch = XmlSchema.Read(sr,SchemaErrorsHandler);

// Create the Reader settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(sch);

// Create an XmlReader specifying the settings.
StringReader xmlData = new StringReader(File.ReadAllText("xmlfile.xml"));
XmlReader xr = XmlReader.Create(xmlData,settings);

// Use the Native .NET Serializer (probably u cud substitute the Xsd2Code serializer here.
XmlSerializer xs = new XmlSerializer(typeof(SerializableClass));
var data = xs.Deserialize(xr);