简体   繁体   English

在验证方法中使用.xsd文件

[英]using an .xsd file in a validation method

I have created a class in order to validate some XML. 我创建了一个类来验证一些XML。 Within that class I have a validation method. 在该类中,我有一个验证方法。 I also have a .xsd file which contains my XML schema. 我还有一个.xsd文件,其中包含我的XML模式。 I've been told that to use this file I must "Load the xsd file into a string" 有人告诉我要使用此文件,我必须“将xsd文件加载到字符串中”

How do you load an xsd file into a string? 如何将xsd文件加载到字符串中?

Without more context, I have no idea what Load the xsd file into a string actually means, but there are far simpler methods to validate an XML. 没有更多的上下文,我不知道Load the xsd file into a string实际上意味着什么,但是有更简单的方法来验证XML。

var xDoc = XDocument.Load(xmlPath);
var set = new XmlSchemaSet();

using (var stream = new StreamReader(xsdPath))
{
    // the null here is a validation call back for the XSD itself, unless you 
    //  specifically want to handle XSD validation errors, I just pass a null and let 
    //  an exception get thrown as there usually isn't much you can do with an error in 
    //  the XSD itself
    set.Add(XmlSchema.Read(stream, null));                
}

xDoc.Validate(set, ValidationCallBack);

Then you just need a method called ValidationCallBack in your class to be your handler for any validation failures (you can name it whatever you want, but delegate parameter the Validate() method above has to reference this method): 然后,您只需要在类中使用一个称为ValidationCallBack的方法来作为任何验证失败的处理程序(可以随意命名,但上面的Validate()方法的委托参数必须引用此方法):

public void ValidationCallBack(object sender, ValidationEventArgs e)
{
    // do something with any errors
}

you can try with this code 您可以尝试使用此代码

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add("....", "youXsd.xsd");
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(YourSettingsValidationEventHandler);

        XmlReader books = XmlReader.Create("YouFile.xml", settings);

        while (books.Read()) { }


       //Your validation
       static void YourSettingsValidationEventHandler(object sender, ValidationEventArgs e)
       {

       }

2 If you want just load you can use StreamReader and ReadToEnd 2如果只想加载,则可以使用StreamReader和ReadToEnd

It is quite easy to read the entire file into a string: 将整个文件读取为字符串非常容易:

string schema;
using(StreamReader file = new StreamReader(path)
{
    schema = file.ReadToEnd();
}

Hope this helps you in your quest. 希望这对您的追求有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM