Validating an XML against referenced XSD in C#

后端 未结 5 618
天命终不由人
天命终不由人 2020-11-22 13:33

I have an XML file with a specified schema location such as this:

xsi:schemaLocation=\"someurl ..\\localSchemaPath.xsd\"

I want to validate

5条回答
  •  有刺的猬
    2020-11-22 14:14

    You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

    using System.Xml;
    using System.Xml.Schema;
    using System.IO;
    
    public class ValidXSD
    {
        public static void Main()
        {
    
            // Set the validation settings.
            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);
    
            // Create the XmlReader object.
            XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
    
            // Parse the file. 
            while (reader.Read()) ;
    
        }
        // Display any warnings or errors.
        private static void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
                Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
            else
                Console.WriteLine("\tValidation error: " + args.Message);
    
        }
    }
    

提交回复
热议问题