Tuesday, June 15, 2010

Validating XML with an XSD using LINQ

So how do you validate an XML document that you get with a particular XSD?.
One way you can do is with LINQ to XML with these steps.
1) Create a XmlSchemaSet
2) Add the schemas that your document needs to confirm to
3) Call the validate method of the XDocument

So here is the example code.

//Load an xml document
XDocument doc = XDocument.Load(@"C:\test.xml");

//Define the schema set
XmlSchemaSet set = new XmlSchemaSet();

//Add the schema to the set
set.Add(string.Empty, @"C:\test.xsd");

//A variable to test whether our document is valid
bool isValid = true;

//Cal the validate method
//Note that I am using a lambda function , alternativley you can use
//pass in a delegate method as in the traditional method :)
doc.Validate(set, (o, e) => { isValid = false; });

//Print out the result

That's it !!.

So what if you want a WCF service to validate this?...you can accept a stream or a string as the input, create the XDocument and then validate it.

Another way you can enforce the validation is generate a class hierarchy that confirms to the XSD and expose that has the parameter of the WCF method.
In this case the client has no other choice but to use the class types, and if the input you get to the WCF service does not serialize correctly to the XML confirming to the XSD an error will be thrown.

No comments:

Post a Comment