Writing and validating XML at the same time

I have a Write method that serializes objects that use XmlAttributes. This is pretty standard:

private bool WriteXml(DirectoryInfo dir) { var xml = new XmlSerializer(typeof (Composite)); _filename = Path.Combine(dir.FullName, _composite.Symbol + ".xml"); using (var xmlFile = File.Create(_filename)) { xml.Serialize(xmlFile, _composite); } return true; } 

Besides trying to read the file I just wrote (using the Schema validator), can I do an XSD WHILE check when XML is being written?

I can mess with memory streams before writing them to disk, but it seems that .Net usually has an elegant way to solve most problems.

+4
source share
1 answer

The way I did it looks like this for everyone who is interested in:

 public Composite Read(Stream stream) { _errors = null; var settings = new XmlReaderSettings(); using (var fileStream = File.OpenRead(XmlComponentsXsd)) { using (var schemaReader = new XmlTextReader(fileStream)) { settings.Schemas.Add(null, schemaReader); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += OnValidationEventHandler; using (var xmlReader = XmlReader.Create(stream, settings)) { var serialiser = new XmlSerializer(typeof (Composite)); return (Composite) serialiser.Deserialize(xmlReader); } } } } private ValidationEventArgs _errors = null; private void OnValidationEventHandler(object sender, ValidationEventArgs validationEventArgs) { _errors = validationEventArgs; } 

Then, instead of writing XML to a file using a memory stream, do something like:

 private bool WriteXml(DirectoryInfo dir) { var xml = new XmlSerializer(typeof (Composite)); var filename = Path.Combine(dir.FullName, _composite.Symbol + ".xml"); // first write it to memory var memStream = new MemoryStream(); xml.Serialize(memStream, _composite); memStream.Position = 0; Read(memStream); if (_errors != null) { throw new Exception(string.Format("Error writing to {0}. XSD validation failed : {1}", filename, _errors.Message)); } memStream.Position = 0; using (var outFile = File.OpenWrite(filename)) { memStream.CopyTo(outFile); } memStream.Dispose(); return true; } 

This way you always check the circuit before anything is written to disk.

+1
source

All Articles