How to: validate XML doc in memory with Schema

Author: Jon aka Poor Guy / Labels:

First come across this when I try to validate the xml.
http://msdn.microsoft.com/en-us/library/ms162371.aspx
But it doesn't solve my problem with in memory xml validation. So I change around the code a bit and come out with this mess, but it works.

try{
//First load the xml and the schema using xmldocument
XmlDocument myXML = new XmlDocument();
myXML.PreserveWhitespace = true;
myXML.Load(textBoxValidateXML.Text);

XmlDocument mySchema = new XmlDocument();
mySchema.PreserveWhitespace = true;
mySchema.Load(textBoxSchema.Text);

//decrypt the file
Encryption myDecrypt = new Encryption("wow");
myDecrypt.Decrypt(myXML);
myDecrypt.Decrypt(mySchema);

//add the schema to the xml
myXML.Schemas.Add("http://www.w3.org/2001/XMLSchema", new XmlTextReader(new System.IO.StringReader(mySchema.InnerXml)));
//add validation event handler
ValidationEventHandler eventHandler = new ValidationEventHandler ValidationEventHandler);
//validate
myXML.Validate();
}
catch(Exception ex) {
//error handler
}


---------------------------------------
the ValidationEventHandler can be very simple

static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show("ERROR: {0}", e.Message);
break;
case XmlSeverityType.Warning:
MessageBox.Show("Warning {0}", e.Message);
break;
}
}

0 comments: