The easiest way, in my opinion, is to use the XmlValidatingRe ader 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 XmlValidatingRe ader before using it to validate the XML.
Here's a code sample which might help:
(Caveat: I set the XmlParserContex t to "null", which may cause issues -- I
haven't actually tested this code. You might want to research the
XmlParserContex t class and supply an instance of this class to the
XmlValidatingRe ader ctor as appropriate.)
Hopefully, this will put you in the right direction!
public class XmlValidator
{
public XmlValidator(st ring xmlFragment, string pathToXsd)
{
XmlValidatingRe ader xmlValidator = new
XmlValidatingRe ader(xmlFragmen t, XmlNodeType.Ele ment, null);
XmlSchemaCollec tion xsdCollection = new
XmlSchemaCollec tion();
if (File.Exists(pa thToXsd))
{
xsdCollection.A dd("urn:my-schema", pathToXsd);
xmlValidator.Sc hemas.Add(xsdCo llection);
}
xmlValidator.Va lidationType = ValidationType. Schema;
vr.ValidationEv entHandler += new
ValidationEvent Handler(MyValid ationHandler);
while (xmlValidator.R ead())
{
// optional element examination here;
// The ValidationEvent event is raised whenever an
error is encountered
}
}
public static void MyValidationHan dler(object sender,
ValidationEvent Args 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.
"Dave" <da**@telco.co. uk> wrote in message
news:eS******** ******@TK2MSFTN GP10.phx.gbl...
Obviously that's the first place I looked, but I can't make sense of it.
There seem to be a plethora of options for validation and I can't get any
to work.
"Microsoft News" <ch**********@c omcast.net> wrote in message
news:eh******** ******@TK2MSFTN GP10.phx.gbl... Look into 'XMLValidatingR eader' in the framework.
SBC
"Dave" <da**@telco.co. uk> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. .. Hi,
I'm really confused as to how to validate XML fragments against a
schema in C#.
I am creating XML through an automated process and have an .xsd which
was given to me to validate against.
Can someone give me some clue as to how to validate my XML string against this schema document? Is there some great secret that I'm missing?
Thanks,
Dave