Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating an XML against an embedded XSD in C#

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.
like image 717
Robert Strauch Avatar asked Oct 22 '25 06:10

Robert Strauch


1 Answers

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
}
like image 64
Fabio S Avatar answered Oct 23 '25 19:10

Fabio S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!