.. useful peice of code to have
Now we all know that Sharepoint is very XML Centric. I am in the midst of writing an interesting commandline utility that will make managing profiles darned easy. And as you know, once managing user profiles is easy, audience targeting becomes easy - huge benefit.
But that is not what this post is all about. See the issue is, frequently you will write a program that will expect some XML that must meet a certain standard. Usually that validation is done using an XSD Schema, so the Q is, how do you validate an XML file with a given XSD schema?
Here is a little function for your quiver -
public static bool IsXmlValid(string xmlFile, string xmlSchema)
{
XmlSchemaSet schemaSet = new XmlSchemaSet() ;
schemaSet.Add("", XmlReader.Create(xmlSchema));
Stream docStream =
new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
XmlReaderSettings settings = new XmlReaderSettings() ;
settings.Schemas.Add(schemaSet) ;
settings.ValidationType = ValidationType.Schema;
XmlReader xRead = XmlReader.Create(docStream, settings) ;
bool toReturn = false;
try
{
while (xRead.Read())
{
// do nothing :-/
}
toReturn = true;
}
catch (XmlSchemaValidationException xExcp)
{
Console.WriteLine(
"Input document " + xmlFile + " does not match the schema", true);
Console.WriteLine(xExcp.ToString(), true);
}
return toReturn;
}
Nice eh?
I'd also recommend reading a quick little modification to the above code, where you can embed the XSD's or other stuff as resources in your dll.