3

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.
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

4 Answers4

3

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
}
Fabio S
  • 1,124
  • 6
  • 8
1

You can use the XmlReaderSettings.Schemas property to specify which schema to use. The schema can be loaded from a Stream.

var schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.contoso.com/books", new XmlTextReader(xsdStream));

var settings = new XmlReaderSettings();
settings.Schemas = schemaSet;

using (var reader = XmlReader.Create(xmlStream, settings))
{
    while (reader.Read());
}
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
0

You could declare the XSD as an embedded resource and load it via GetManifestResourceStream as described in this article: How to read embedded resource text file

Community
  • 1
  • 1
gtonic
  • 2,295
  • 1
  • 24
  • 32
0

Yes, this is possible. Read the embedded resource file to string and then create your XmlSchemaSet object adding the schema to it. Use it in your XmlReaderSettings when validating.

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
japesu
  • 134
  • 1
  • 10