Validate XML Using .NET 4.0

I wanted to validate that some XML conforms to a schema. I found some examples using XmlValidatingReader but that is obsolete. Instead, you use an ordinary XmlReader with special XmlReaderSettings. In this case, I store the schema files as resources in the assembly. Here is my code:

// Create reader setttings with our schema definition.
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("urn:riv:ehr:patientsummary:1", XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("EhrExtractService.UnitTests.ISO_dt.xsd")));
settings.Schemas.Add("urn:riv:ehr:patientsummary:1", XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("EhrExtractService.UnitTests.ehr_patientsummary_1.0.xsd")));
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += (o, e) =>
        Console.WriteLine("{0}", e.Message);
// Load the serialized xml and validate.
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
XDocument document = XDocument.Load(reader);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.