Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading XDocument while validating against schema in .NET 3.5

Tags:

.net

Input is xml as a string and I have a XSD schema to verify against.

I wish to validate the xml against the XSD schema while loading the xml into an XDocument (requirement since I need to do parsing with Linq afterwards).

Anyone has a small code-snippet?

like image 762
Tim Skauge Avatar asked May 05 '09 07:05

Tim Skauge


2 Answers

Load the document, and then use XDocument.Validate, passing in an XmlSchemaSet to represent the schemas you want to validate against, and a ValidationEventHandler to react appropriately to any validation problems.

There's an MSDN article with a complete example and discussion.

like image 175
Jon Skeet Avatar answered Oct 11 '22 17:10

Jon Skeet


Just a note about the above answer. It is correct but can be confusing. XDocument.Validate is an extension method that exists in the System.Xml.Schema namespace. If you do not use this namespace then the Validate method will not appear in intellisense. Just thought I'd help those who were as confused as I was. :)

like image 37
Jordan Avatar answered Oct 11 '22 19:10

Jordan