Home > Backend Development > C++ > How to Validate XML against a Referenced XSD Schema in C#?

How to Validate XML against a Referenced XSD Schema in C#?

Linda Hamilton
Release: 2025-01-21 18:57:09
Original
616 people have browsed it

How to Validate XML against a Referenced XSD Schema in C#?

C# XML Validation Against Referenced XSD Schema

Ensuring XML document validity against a defined schema is crucial. This article demonstrates C# XML validation using the XmlDocument class against an XSD schema.

Unlike default behavior, XmlDocument doesn't automatically validate against schemas embedded within the XML. To enable this, we'll configure XmlReaderSettings. Specifically, we set ValidationType to Schema and utilize ValidationFlags to process inline schemas, schema locations, and report warnings.

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
Copy after login

Next, create an XmlReader using these settings and register a ValidationEventHandler to capture validation results.

XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
Copy after login

The ValidationCallBack method processes validation events:

private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
    if (args.Severity == XmlSeverityType.Warning)
        Console.WriteLine("\tWarning: " + args.Message);
    else
        Console.WriteLine("\tValidation error: " + args.Message);
}
Copy after login

This streamlined method automatically validates the XML against its embedded schema, eliminating the need for manual schema loading into the XmlDocument object. The ValidationCallBack function provides clear warnings and error messages.

The above is the detailed content of How to Validate XML against a Referenced XSD Schema in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template