如何在不将所有XML文档加载到内存的情况下针对XSD验证XML文件? [英] How to validate XML file against XSD without loading all XML document into memory?

查看:76
本文介绍了如何在不将所有XML文档加载到内存的情况下针对XSD验证XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证xml文档。它的大小非常大。我已经定义了XSD架构来验证这个xml文档。

I need to validate an xml document. Its size is very large. I have defined XSD schema to validate this xml document.

目前我正在使用ReadXML方法将数据加载到XSD中。由于数据非常大,因此消耗了大量内存。还有CPU时间。

Currently I am using ReadXML method to load data into XSD. Since data is very large, a lot of memory is getting consumed. Also CPU time.

如何在不将所有XML文档加载到内存的情况下针对XSD验证XML文件?

How can i validate XML file against XSD without loading all XML document into memory?

是否有专门的XSD验证类一个不会加载和反序列化整个XML的文档(更像是一个像流一样工作)?

Are there any specialized classes for XSD validation of a document that will not load and deserialize the whole XML (more working like a stream)?

提前谢谢

推荐答案

然后需要将模式加载到XmlSchemaSet中,但是要验证的XML文档可以通过验证XmlReader进行解析,该模板只是以较低的内存占用量逐节点地拉入。所以代码看起来像

Well the schemas need to be loaded into an XmlSchemaSet but the XML document you want to validate can be parsed through by a validating XmlReader which simply pulls in node by node with a low memory footprint. So code looks like

            XmlReaderSettings xrs = new XmlReaderSettings();

            xrs.ValidationType = ValidationType.Schema;

            xrs.Schemas.Add(null, "schema.xsd");

            xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

            bool valid = true;

            xrs.ValidationEventHandler += (sender, vargs) =>
            {

                Console.WriteLine("{0}: {1}", vargs.Severity, vargs.Message);

                if (vargs.Severity == XmlSeverityType.Error)
                {

                    valid = false;

                }

            };

            // now read through your input with those settings e.g.

            using (XmlReader xr = XmlReader.Create("input.xml", xrs))
            {

                while (xr.Read()) { }

            }
            Console.WriteLine("Document is valid: {0}.", valid);
        }


另请参阅 http://msdn.microsoft。 com / zh-CN / library / as3tta56

See also http://msdn.microsoft.com/en-us/library/as3tta56.


这篇关于如何在不将所有XML文档加载到内存的情况下针对XSD验证XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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