Home >Backend Development >C++ >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.
<code class="language-csharp">XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;</code>
Next, create an XmlReader
using these settings and register a ValidationEventHandler
to capture validation results.
<code class="language-csharp">XmlReader reader = XmlReader.Create("inlineSchema.xml", settings); reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);</code>
The ValidationCallBack
method processes validation events:
<code class="language-csharp">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); }</code>
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!