Home >Backend Development >C++ >How to Automatically Validate an XML File Against its Referenced XSD in C#?
Validate XML against referenced XSD in C#
Question:
How to automatically validate an XML file containing a specified schema location in C# without explicitly specifying the schema to validate, like Visual Studio does when opening the file?
Answer:
To automatically validate an XML file against a referenced XSD in C#, without explicitly specifying the schema, you need to create an instance of XmlReaderSettings
and pass it to it when creating the XmlReader
. Validation errors can be received by subscribing to settings
in ValidationEventHandler
.
Here is a sample code demonstrating this method:
<code class="language-csharp">using System.Xml; using System.Xml.Schema; using System.IO; public class XML验证 { 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>
Using this method, validation will be performed automatically based on the pattern specified in the XML file's xsi:schemaLocation
attribute.
The above is the detailed content of How to Automatically Validate an XML File Against its Referenced XSD in C#?. For more information, please follow other related articles on the PHP Chinese website!