Jan Tacci Jan Tacci - 4 years ago 137
C# Question

Validating Serialized Xml Prior To Saving To A File

I have an Xml schema, CustomerData.xsd, that I use Microsoft's xsd.exe to create the class CustomerData.

My program reads in an Xml file uses XmlSerializer to get an instance of CustomerData using the following code:

XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));
TextReader textReader = new StreamReader(fileName);
CustomerData customerData = (CustomerData)serializer.Deserialize(textReader);
textReader.Close();


While my program runs customerData can be modified and there is a possibility that some of the values might not be valid according to the schema.

Before the user saves this data back to a file I want to be able to validate it. How can I validate the data before saving?

Note - I compile the schema as an Embedded Resource so I can use code such as the following to get to the schema:

Assembly myAssembly = typeof(CustomerData).Assembly;
Stream schemaStream = myAssembly.GetManifestResourceStream(schemaResourceName);


I also know how to make a validating SchemaReader:

XmlReader schemaReader = XmlReader.Create(schemaStream);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, schemaReader);
settings.ValidationType = ValidationType.Schema;


I just don't know what do do next.

Answer Source

Making minimal changes to your code:

// Get the data that the customer has entered
TextReader textReader = new StreamReader(fileName);

// Create the validating reader
XmlReader schemaReader = XmlReader.Create(schemaStream);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, schemaReader);
settings.ValidationType = ValidationType.Schema;
var documentReader = XmlReader.Create(textReader, settings);

// Use the validating reader to read
try 
{
    while (documentReader.Read())
    {
    }
}
catch (XmlSchemaValidationException ex) 
{
    //do logging or whatever here
}

But it is slightly less code to use an XmlDocument rather than an XmlReader:

 // Get the data that the customer has entered
TextReader textReader = new StreamReader(fileName);

// Create an XmlDocument to read the data
XmlDocument xmlDocument = new XmlDocument();

// Attach the schema to the XmlDocument
xmlDocument.Schemas = new XmlSchemaSet();
xmlDocument.Schemas.Add(null, new XmlTextReader(schemaStream));

// Load the document and validate it
xmlDocument.Load(textReader);
List<String> errors = new List<String>();
xmlDocument.Validate((sender, eventArgs) => errors.Add(eventArgs.Message));
// the errors list will now contain a list of schema errors
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download