Validating XML against referenced XSD in C#
When an XML file with a specified schema location is loaded, it is expected that the file will be automatically validated against the schema in C#. However, manually specifying the schema seems necessary.
In order to validate XML without manually specifying the schema, you must create an instance of XmlReaderSettings
and pass it to XmlReader
on creation. This allows you to subscribe to ValidationEventHandler
in settings to receive validation errors.
Here is a modified code example to achieve this:
<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); // 使用指定的验证设置加载 XML 文件。 XmlDocument asset = new XmlDocument(); XmlReader reader = XmlReader.Create("XML_file_path.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>
Using XmlReaderSettings
you can automatically validate XML files against referenced XSDs without explicitly specifying the schema.
The above is the detailed content of How to Automatically Validate XML Against a Referenced XSD in C#?. For more information, please follow other related articles on the PHP Chinese website!