Validating XML against an XSD schema

I have a new job. Well, I say "new" but I actually started in December 2005. Anyway, this "new" job requires me to develop compact framework apps. Seeing as Delphi doesn't support CF I am developing my application in VS2005, it's a really nice tool but I miss ECO so much!

One thing I had to do was to write an XML importer routine. This would retrieve an XML file detailing tasks due for the next seven days and then import it into the PPC's database. Because I am not responsible for generating the XML, and because it is good practise anyway, I decided to create an XSD file to validate the XML. PDA's have very little storage resources (the flash card is shared between disk and memory) so I decided to read the XML file a line at a time using the XmlReader so that the contents don't exist on the flash memory twice (disk + memory), another benefit of this approach being that I can read it directly from a ZIP file too!

In dotnet V2 the class XmlValidatingReader is obsolete, not that it would have been much good anyway considering it is not implemented in V1 of the compact framework. After some playing around I was finally able to read the XSD information from a resourced embedded into my app, and read the XML one line at a time whilst validating it against that XSD file.

Here it is:

//1 Get a stream containint the XSD
Stream xsdStream = GetType().Assembly.GetManifestResourceStream("Eden.HandheldVendor.TaskFlow.DataImport.xsd");
//2) Create an XmlTextReader that uses this stream
XmlReader xsdReader = new XmlTextReader(xsdStream);
//Create an XmlSchema from the embedded XSD
System.Xml.Schema.XmlSchema xsdSchema = System.Xml.Schema.XmlSchema.Read(xsdReader, null);

//4) Create some XmlReaderSettings that use this XmlSchema
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas.Add(xsdSchema);

//5) Set an event for validation errors
readerSettings.ValidationEventHandler +=
new System.Xml.Schema.ValidationEventHandler(readerSettings_ValidationEventHandler);

//6) Create the xmlReader that will read the XML file using our reader settings
XmlReader xmlReader = XmlTextReader.Create(xmlStream, readerSettings);

//7) Now read the file
while (xmlReader.Read())

Comments

Popular posts from this blog

Connascence

Convert absolute path to relative path

Printing bitmaps using CPCL