I have an XML file with a specified schema location such as this:
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
I want to validate in C#. Visual Studio, when I open the file, validates it against the schema and lists errors perfectly. Somehow, though, I can't seem to validate it automatically in C# without specifying the schema to validate against like so:
XmlDocument asset = new XmlDocument(); XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath"); XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler); asset.Schemas.Add(schema); asset.Load(filename); asset.Validate(DocumentValidationHandler);
Shouldn't I be able to validate with the schema specified in the XML file automatically ? What am I missing ?
You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.
XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document. The System. Xml.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With