Validating an XML against an embedded XSD in C#

2020-07-23 08:16发布

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.

4条回答
贪生不怕死
2楼-- · 2020-07-23 09:00

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());
}
查看更多
劫难
3楼-- · 2020-07-23 09:02

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.

查看更多
你好瞎i
4楼-- · 2020-07-23 09:13

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
}
查看更多
够拽才男人
5楼-- · 2020-07-23 09:19

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

查看更多
登录 后发表回答