如何使用 XSD2CODE 生成的 C# 类

发布于 2024-11-16 19:27:15 字数 144 浏览 2 评论 0原文

我是 XSD 世界的新手,我使用过 XML,但没有太多编程方面的工作。 我已使用 XSD2Code 成功生成了 C# 类。有人可以指导我如何使用 C# 使用这些生成的类并使用我的 XML 进行验证吗?

代码片段将受到高度赞赏。

谢谢和问候。

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 snippet would be hightly appreciated.

Thanks and regards.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-11-23 19:27:16

查看生成的 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);

Looking at the generated Serialize and Deserialize methods of Xsd2Code, it doesn't look like it does schema validation. I haven't used Xsd2Code much, so I might be wrong.

But what you could do is use the XmlReaderSettings class to set up the schemas the XML will use.

// 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);
百变从容 2024-11-23 19:27:15

验证 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,否则它不会按原样编译。

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

    }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文