The easiest way, in my opinion, is to use the XmlValidatingReader class --
specifically, the overload that takes an XML fragment and a parser context.
You need to add the schema to the Schemas and ValidatingType attributes of
the XmlValidatingReader before using it to validate the XML.
Here's a code sample which might help:
(Caveat: I set the XmlParserContext to "null", which may cause issues -- I
haven't actually tested this code. You might want to research the
XmlParserContext class and supply an instance of this class to the
XmlValidatingReader ctor as appropriate.)
Hopefully, this will put you in the right direction!
public class XmlValidator
{
public XmlValidator(string xmlFragment, string pathToXsd)
{
XmlValidatingReader xmlValidator = new
XmlValidatingReader(xmlFragment, XmlNodeType.Element, null);
XmlSchemaCollection xsdCollection = new
XmlSchemaCollection();
if (File.Exists(pathToXsd))
{
xsdCollection.Add("urn:my-schema", pathToXsd);
xmlValidator.Schemas.Add(xsdCollection);
}
xmlValidator.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler += new
ValidationEventHandler(MyValidationHandler);
while (xmlValidator.Read())
{
// optional element examination here;
// The ValidationEvent event is raised whenever an
error is encountered
}
}
public static void MyValidationHandler(object sender,
ValidationEventArgs args)
{
// Perform handling for validation error here
}
}
--
----
Doug Erickson [MSFT], Platform SDK UA
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use. 2004 Microsoft Corporation. All rights
reserved.