XML documents can reference external schemas using the xsi:schemaLocation
attribute. However, when doing XML validation in C#, you may want to leverage the schema specified in the XML file rather than manually loading it.
In order to implement automatic verification based on inline mode, you can use the following methods:
<code class="language-csharp">using System.Xml; using System.Xml.Schema; using System.IO; public class ValidXSD { public static void Main() { // 初始化 XmlReaderSettings 实例。 XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings }; // 注册验证事件处理程序。 settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // 使用设置创建 XmlReader。 XmlReader reader = XmlReader.Create("inlineSchema.xml", settings); // 处理 XML 文件。 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>
This method uses the ValidationType
attribute to specify schema validation, and the associated ValidationFlags
to indicate the use of inline schema and schema placement. ValidationEventHandler
is used to handle any validation errors or warnings that may occur during parsing.
The above is the detailed content of How Can I Parse XML with Embedded Schema Validation in C#?. For more information, please follow other related articles on the PHP Chinese website!