需要使用XmlReaderSettings类在C#中进行XML验证 [英] Need for XML Validation in C# using XmlReaderSettings class

查看:577
本文介绍了需要使用XmlReaderSettings类在C#中进行XML验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在针对读取的XML模式验证XML文件,该XML模式需要编写以下代码(使用XmlReaderSettings类)


 XmlReaderSettings xmlSettings =  XmlReaderSettings();
xmlSettings.Schemas =  System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add(" ,xsdUri);
xmlSettings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xmlUri,xmlSettings);
同时(reader.Read()); 


但是我不明白的是,为什么我们可以通过代码来验证xml,而在Visual Studio中可以通过在要验证的xml文件中添加XML模式名称空间来验证xml?

在此先感谢

解决方案

好吧,我似乎找到了令人满意的理由来解释通过代码进行验证.
其原因很简单,在某些情况下,我们不希望架构的用户简单地忽略静态验证过程中架构所引发的错误(即,通过在xml文件中指定架构名称空间在Visual Studio中进行验证;并且不通过以下方式进行额外的验证)代码存在).我们希望用户严格遵守模式,因此我们通过代码添加了额外的验证,只要xml中存在错误,该验证就会抛出异常.直到用户更正xml,他才能继续.

Hi All ,
I am validating XML files against an XML schema for which I read that the following code needs to be written (using XmlReaderSettings class)


XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add("myNamespace", xsdUri);
xmlSettings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xmlUri, xmlSettings);
while (reader.Read()) ;


but what I don''t understand is why should we validate xmls through the code ,when xmls can be validated in Visual studio by adding the XML schema namespace in the xml file we intend to validate ?

Thanks In Advance

解决方案

Well,I seem to have found a satisfactory reason for why validation through code is done .
Its for the simple reason that ,In certain cases we dont want the users of our schema to simply ignore the errors thrown by the schema during static validation (i.e validation in Visual studio by specifying schema namespace in the xml file ;and no extra validation through code exists).We want the users to strictly adhere to the schema therefore we add extra validation through the code ,which throws an exception whenever there is an error in the xml.Untill the user corrects the xml,he cannot proceed.


这篇关于需要使用XmlReaderSettings类在C#中进行XML验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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