I have a complex schema structure, with multiple schema using the tag. The issue I was having was accessing the schema files that were stored in sub folders (something like /xsd/Person/personcommon.xsd), as the file structure doesn't exist when added as an embedded resource. I have written a .dll to validate the XML file and then de-serialize the file into objects. These objects are called by another application. After searching around I came up with the following to help validate the XML:
public bool ValidateXML(string xmlFilePath)
{
// Set the namespace followed by the folder
string prefix = "MyApp.xsd";
// Variable to determine if file is valid
bool isValid = true;
// Assembly object to find the embedded resources
Assembly myAssembly = Assembly.GetExecutingAssembly();
// Get all the xsd resoruces
var resourceNames = myAssembly.GetManifestResourceNames().Where(name => name.StartsWith(prefix));
try
{
// Load the XML
XDocument xmlDoc = XDocument.Load(xmlFilePath);
// Create new schema set
XmlSchemaSet schemas = new XmlSchemaSet();
// Iterate through all the resources and add only the xsd's
foreach (var name in resourceNames)
{
using (Stream schemaStream = myAssembly.GetManifestResourceStream(name))
{
using (XmlReader schemaReader = XmlReader.Create(schemaStream))
{
schemas.Add(null, schemaReader);
}
}
}
// Call to the validate method
xmlDoc.Validate(schemas, (o, e) => { this.ErrorMessage = string.Format("File failure: There was an error validating the XML document: {0} ", e.Message); isValid = false; }, true);
return isValid;
}
catch (Exception ex)
{
isValid = false;
this.ErrorMessage = string.Format("File failure: There was an error validating the XML document: {0}", ex.ToString());
return isValid;
}
}
The issue I am now having is in my unit tests. Debuging through the code I see exceptions are thrown when schemas.Add() is called, it can't find the referenced XSD files. The weird thing is that it still validates the XML file passed in correctly.
Is this expected behavior and is the code I have written valid / is there a better way I can access these XSD files.