Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate the output of XmlSerializer?

In C# / .NET 2.0, when I serialize an object using XmlSerializer, what's the easiest way to validate the output against an XML schema?

The problem is that it is all too easy to write invalid XML with the XmlSerializer, and I can't find a way to validate the XML that does not look cumbersome. Ideally I would expect to set the schema in the XmlSerializer or to have a XmlWriter that validates.

like image 308
Tim Jansen Avatar asked Mar 09 '10 09:03

Tim Jansen


1 Answers

What about reading it in again using a validating reader

Here's a quick stab at it

Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("<YourXml />"));
var input = mappingAssembly.GetManifestResourceStream(
            "MySchema.xsd"
            ); //This could be whatever resource your schema is           
var schemas = new XmlSchemaSet();            
schemas.Add(
   "urn:YourSchemaUrn",
   XmlReader.Create(
      input
      )
 );

var settings = new XmlReaderSettings
                           {
                               ValidationType = ValidationType.Schema,
                               Schemas = schemas
                           };

settings.ValidationEventHandler += MakeAHandlerToHandleAnyErrors;

var reader = XmlReader.Create(stream, settings);
while (reader.Read()) {} //Makes it read to the end, therefore validates

You'll need to have some handler to do something when there are errors.

like image 71
Mark Dickinson Avatar answered Oct 08 '22 15:10

Mark Dickinson