XML Schema Validation in c#

D

Dave

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
 
D

Dave

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.
 
D

Doug Erickson [MS]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top