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

Pro*_*bie 3 c# xsd

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

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

psu*_*003 5

如果没有更多上下文,我不知道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);
Run Code Online (Sandbox Code Playgroud)

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

public void ValidationCallBack(object sender, ValidationEventArgs e)
{
    // do something with any errors
}
Run Code Online (Sandbox Code Playgroud)