1

我是 XSD 世界的新手,我使用过 XML,但在编程方面并不多。我已经使用 XSD2Code 成功生成了 C# 类。有人可以指导我如何使用 C# 生成的类并使用我的 XML 进行验证。

代码片段将不胜感激。

谢谢并恭祝安康。

4

2 回答 2

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 文档内容。您将找到设置了错误/警告的ErrorMessage和属性(如果有)。WarningMessage为了工作,XML 文档必须xmlns声明正确的。请注意,我的课程默认使用 log4net 作为记录器机制,因此除非您也使用 log4net,否则它不会按原样编译。

于 2011-06-23T08:58:37.010 回答
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);
于 2011-06-23T09:06:49.937 回答