views:

167

answers:

2

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.

A: 

You could use XmlReader to validate a XML file against an XSD schema.

Darin Dimitrov
True, but that means that I have to write the XML, store it somewhere, and read it again. I had hoped that there was an easier way to do it on-the-fly.
Tim Jansen
XmlSerializer does not support validating against an XSD schema as it is supposed generate the XML from an object which should always be valid.
Darin Dimitrov
That's not the case though. It seems like required elements are omitted if their value is null. And there are probably other things not supported by XmlSerializer (length and pattern constraints for strings, uniqueness , key references).
Tim Jansen
Can't you add attributes to the properties of classes you are serializing to make them required, then the corresponding elements will be included but without a value. When deserializing this sort of thing makes the difference between a null value and an empty string for instance.
Mark Dickinson
Like this [XmlElement (IsNullable = true)]
Mark Dickinson
+2  A: 

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.

Mark Dickinson