Validating CDA documents in C# seems to be a bit tricky… At first, I started out just copying the infrastructure and processable schemas to a project and creating the code to use those schemas to validate. Unfortunately, I kept getting errors like “Missing complexType ‘II’ used in restriction base”. The II type is defined in datatypes-base, and the element it was error out on was the POCD_MT000040.InfrastructureRoot.typeId complex type.
I still have no idea what the issue is here… The schemas validate without problem in Eclipse, Oxygen and even XMLSpy.
I ended up having to flatten the schemas into a single file. I believe the issue has something to do with namespaces that I don’t fully understand; so if anyone out here has the answer, please comment.
After flattening the structure of the schemas into a single file, it started validating without problem using the following code:
public static bool ValidateCDA(string content)
{
List<string> validationErrors = new List<string>();
byte[] contentBytes = ASCIIEncoding.ASCII.GetBytes(content);
using (MemoryStream contentStream = new MemoryStream(contentBytes))
{
XmlValidatingReader validationReader = new XmlValidatingReader(new XmlTextReader(contentStream));
validationReader.XmlResolver = new XmlUrlResolver();
validationReader.ValidationType = ValidationType.Schema;
// Add CDA xsd
Stream cdaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("My.Namespace.CDA.xsd");
XmlReader cdaReader = XmlReader.Create(cdaStream);
validationReader.Schemas.Add("urn:hl7-org:v3", cdaReader);
validationReader.ValidationEventHandler += new ValidationEventHandler(
delegate(object sender, ValidationEventArgs e)
{
validationErrors.Add(e.Message);
});
while (validationReader.Read()) { }
}
return validationErrors.Count == 0;
}