C# – Validating an XML against an embedded XSD in C#

cvalidationxmlxsd

Using the following MSDN documentation I validate an XML file against a schema: http://msdn.microsoft.com/en-us/library/8f0h7att%28v=vs.100%29.aspx

This works fine as long as the XML contains a reference to the schema location or the inline schema. Is it possible to embed the schema "hard-coded" into the application, i.e. the XSD won't reside as a file and thus the XML does not need to reference it?

I'm talking about something like:

  1. Load XML to be validated (without schema location).
  2. Load XSD as a resource or whatever.
  3. Do the validation.

Best Answer

Try this:

Stream objStream = objFile.PostedFile.InputStream;

// Open XML file
XmlTextReader xtrFile = new XmlTextReader(objStream);

// Create validator
XmlValidatingReader xvrValidator = new XmlValidatingReader(xtrFile);
xvrValidator.ValidationType = ValidationType.Schema;

// Add XSD to validator
XmlSchemaCollection xscSchema = new XmlSchemaCollection();
xscSchema.Add("xxxxx", Server.MapPath(@"/zzz/XSD/yyyyy.xsd"));
xvrValidator.Schemas.Add(xscSchema);

try 
{
  while (xvrValidator.Read())
  {
  }
}
catch (Exception ex)
{
  // Error on validation
}