模式验证XML

aha*_*ron 9 c# xml schema xsd

我有一个XSD文件和一个XML文件,如何检查XML是否在XSD文件中的正确模式中?

我知道类中有一个验证函数XmlDocument,但它需要一个事件处理程序,我需要的只是true或false.

PS我在Visual Studio 2010工作.

aha*_*ron 23

有一个很简单的方法:

private void ValidationCallBack(object sender, ValidationEventArgs e)
{  
    throw new Exception();
}

public bool validate(string sxml)
{
    try
    {
        XmlDocument xmld=new XmlDocument ();
        xmld.LoadXml(sxml);
        xmld.Schemas.Add(null,@"c:\the file location");
        xmld.validate(ValidationCallBack);
        return true;
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:我没有在VS中写这个,所以可能有一些不区分大小写的字,但这个代码有效!