繁体   English   中英

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

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

我创建了一个类来验证一些XML。 在该类中,我有一个验证方法。 我还有一个.xsd文件,其中包含我的XML模式。 有人告诉我要使用此文件,我必须“将xsd文件加载到字符串中”

如何将xsd文件加载到字符串中?

没有更多的上下文,我不知道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);

然后,您只需要在类中使用一个称为ValidationCallBack的方法来作为任何验证失败的处理程序(可以随意命名,但上面的Validate()方法的委托参数必须引用此方法):

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

您可以尝试使用此代码

        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如果只想加载,则可以使用StreamReader和ReadToEnd

将整个文件读取为字符串非常容易:

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

希望这对您的追求有所帮助。

暂无
暂无

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

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