Home >Backend Development >C++ >How to Validate an XML Against a Referenced XSD in C#?
Validate XML with external XSD schema in C#
In C#, validating an XML document against an external XSD schema can usually be accomplished by directly leveraging the information provided in the XML's xsi:schemaLocation
attribute. However, in some cases, manual intervention is required to perform verification.
In order to automatically validate XML against a specified schema, you need to create an instance of XmlReaderSettings
and pass it to it when creating the XmlReader
. By setting ValidationType
to Schema
, and ValidationFlags
to include ProcessInlineSchema
, ProcessSchemaLocation
, and ReportValidationWarnings
, the reader will automatically process and validate the XML against the schema referenced in the xsi:schemaLocation
attribute.
Here is a code snippet demonstrating this approach:
<code class="language-csharp">using System.Xml; using System.Xml.Schema; using System.IO; public class ValidXSD { public static void Main() { // 设置验证设置。 XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // 创建XmlReader对象。 XmlReader reader = XmlReader.Create("inlineSchema.xml", settings); // 解析文件。 while (reader.Read()) ; } // 显示任何警告或错误。 private static void ValidationCallBack(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) Console.WriteLine("\t警告:未找到匹配的模式。未进行验证。" + args.Message); else Console.WriteLine("\t验证错误: " + args.Message); } }</code>
The above is the detailed content of How to Validate an XML Against a Referenced XSD in C#?. For more information, please follow other related articles on the PHP Chinese website!