How to Validate xml against XSD in C# windows forms

我们两清 提交于 2020-02-01 08:47:54

问题


All the C# codes available over net are just for read and loading XML and XSD.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"D:\XML\Sample.xml");
xmlDocument.Schemas.Add("http://www.w3.org/2001/XMLSchema", @"D:\XML\Sample.xsd");
xmlDocument.Schemas.Compile();

ValidationEventHandler eventhandler = new ValidationEventHandler(ValidationEventHandler);
xmlDocument.Validate(eventhandler);

if (valid == true)
{
    label1.Text = "Xml Got Validated!!";
}

void ValidationEventHandler(object sender, ValidationEventArgs e)
{
    valid = false;
    switch (e.Severity)
    {
        case XmlSeverityType.Error: label1.Text = "Xml Validation Failed".ToString();
            break;
        case XmlSeverityType.Warning: label1.Text = "Xml Has some warning".ToString();
            break;
    }
}

This actually is not validating my XML just reading even if I don't pass elements that are mandatory it says: "ITS Valid"


回答1:


I use the following and it applies validation successfully:

var xsd = new XmlSchemaSet();

using (var ms = new StringReader(Resources.MyXsd))
{
    using (var reader = XmlReader.Create(ms))
    {
        xsd.Add(XmlSchema.Read(reader, delegate { }));
    }
}

var document = XDocument.Parse(text);

document.Validate(
    xsd, (o, e) =>
        {
            if (e.Severity == XmlSeverityType.Error)
            {
                validationMessages.Add(e.Exception.Message);
            }
        }
);


来源:https://stackoverflow.com/questions/6522319/how-to-validate-xml-against-xsd-in-c-sharp-windows-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!