Please help. I'm been working on this for a week now and don't seem
to be making any headway.
Basically, I'm getting xml which can be in about 8 different schema
(maybe more). I want to run that xml against each schema to see if it
validates. If it does so, I know what kind of xml file it is and I
know how to process it from there. If it doesn't validate against any
of them, well, then I know what to do with the file in that case as
well.
I wrote the following code
class XMLValidator
{
int numErrors;
string msgError;
Dictionary<string, XmlReaderSettings> dictSchemaSet;
public XMLValidator(string strXSDDirectoryPath)
{
msgError = "";
dictSchemaSet = null;
dictSchemaSet = getSchemaSet(strXSDDirectoryPath);
}
private Dictionary<string,XmlReaderSettings> getSchemaSet
(string strXSDDirectoryPath)
{
Dictionary<string,XmlReaderSettings> dictSchemaCollection
= new Dictionary<string,XmlReaderSettings>();
DirectoryInfo di = new DirectoryInfo(strXSDDirectoryPath);
FileInfo[] rgFiles = di.GetFiles("*.xsd");
foreach (FileInfo fi in rgFiles)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new
ValidationEventHandler(this.ValidationEventHandler);
settings.ValidationType = ValidationType.Schema;
string schemaPath = strXSDDirectoryPath+"\\"+fi.Name;
settings.Schemas.Add(fi.Name,XmlReader.Create
(schemaPath));
dictSchemaCollection.Add(fi.Name,settings);
}
return dictSchemaCollection;
}
private void ValidationEventHandler(object sender,
ValidationEventArgs args)
{
msgError = msgError + "\r\n" + args.Message;
numErrors++;
}
public string getSchema(string strXMLpath)
{
string strSchemaIdentified = "unknown";
numErrors = 0;
foreach (KeyValuePair<string, XmlReaderSettings> settings
in dictSchemaSet)
{
using (XmlReader xmlValidatingReader = XmlReader.Create
(strXMLpath, settings.Value))
{
while(xmlValidatingReader.Read()){}
if (numErrors == 0)
{
strSchemaIdentified = settings.Key;
break;
}
else
numErrors = 0;
}
}
return strSchemaIdentified;
}
}
However, when I run xml against it, the code always reports that the
xml validates against the first schema in the dictionary. I tested
the schema in XMLSpy. This shouldn't be happening.
And, like I said, I've been banging my head against the wall on this
for a week. Please give me a hand.
Thanks