CdaLib 1.21.0
dotnet add package CdaLib --version 1.21.0
NuGet\Install-Package CdaLib -Version 1.21.0
<PackageReference Include="CdaLib" Version="1.21.0" />
<PackageVersion Include="CdaLib" Version="1.21.0" />
<PackageReference Include="CdaLib" />
paket add CdaLib --version 1.21.0
#r "nuget: CdaLib, 1.21.0"
#:package CdaLib@1.21.0
#addin nuget:?package=CdaLib&version=1.21.0
#tool nuget:?package=CdaLib&version=1.21.0
CdaLib
Proprietary Software. This software is proprietary. Unauthorized copying, distribution, modification, or use is prohibited. All rights reserved. This notice applies to the CdaLib and CdaLib.Rendering codebases and to all documentation in this repository.
A .NET library for parsing and generating C-CDA (Consolidated Clinical Document Architecture) documents with full ONC 170.315(b)(1) Transitions of Care compliance.
๐ Features
- โ Parse C-CDA XML documents into domain models
- โ Generate C-CDA XML documents from domain models
- โ Section Filtering - Selectively include/exclude sections during parsing and compilation โญ NEW
- โ FHIR Bundle Support - Convert FHIR R4 bundles to C-CDA documents and vice versa โญ NEW
- โ Render C-CDA documents as beautiful, responsive HTML reports
- โ XML to HTML - Direct conversion from C-CDA XML to HTML โญ NEW
- โ Validate documents against XSD schemas and ONC conformance requirements
- โ JSON Validation API - Validate C-CDA documents and get detailed results in JSON format โญ NEW
- โ Multi-Document Type Support - CCD, Discharge Summary, Referral Note, and more
- โ ONC Certification Ready - Full sender/receiver conformance validation
- โ C-CDA 2.1 & USCDI V3 Compliant
๐ Quick Start
Installation
Core Library:
dotnet add package CdaLib --version 1.21.0
HTML Rendering (Optional):
dotnet add package CdaLib.Rendering --version 1.21.0
Or via Package Manager:
Install-Package CdaLib -Version 1.21.0
Install-Package CdaLib.Rendering -Version 1.21.0
Basic Usage
using CdaLib;
using CdaLib.Parsing;
using CdaLib.Domain;
// Create a service for Continuity of Care Document
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
// Create your clinical data
var ccd = new Ccd
{
Patient = new Patient { FirstName = "John", LastName = "Doe", /* ... */ },
Problems = new List<Problem> { /* ... */ },
Medications = new List<Medication> { /* ... */ },
Allergies = new List<Allergy> { /* ... */ }
};
// Generate C-CDA XML with sender conformance validation
var (errors, xmlDoc) = service.Export(ccd);
if (errors.Any())
{
// Handle validation errors
foreach (var error in errors)
{
Console.WriteLine($"{error.ProblemType}: {error.Reason}");
}
}
// Save to file
service.ExportToFile(ccd, "output.xml");
// Parse an existing C-CDA document with receiver conformance validation
var (importErrors, parsedCcd) = service.Import("input.xml");
// NEW: Validate C-CDA XML and get JSON results with line numbers
var validationJson = service.Validate("input.xml");
// Or validate from XML string
var validationJson2 = service.Validate(xmlString);
// NEW: Import with FileInfo overload
var fileInfo = new FileInfo("input.xml");
var (errors, ccd) = service.Import(fileInfo);
// NEW: Render as responsive HTML medical report
var renderer = new CdaLib.Rendering.CdaHtmlRenderer(CcdaDocumentTypes.ContinuityOfCareDocument);
renderer.RenderToFile(parsedCcd, "patient-report.html");
// NEW: Convert FHIR Bundle to C-CDA
var fhirBundle = GetFhirBundle(); // Your FHIR R4 Bundle
var (fhirErrors, fhirXml) = service.ExportFromFhir(fhirBundle);
// NEW: Convert CCD to FHIR Bundle
using CdaLib.Mapping;
var fhirBundleFromCcd = CcdToFhirMapper.MapToFhirBundle(parsedCcd);
// NEW: Convert C-CDA XML directly to HTML
var htmlRenderer = new CdaLib.Rendering.CdaHtmlRenderer(CcdaDocumentTypes.ContinuityOfCareDocument);
var html = htmlRenderer.RenderXmlToHtml(xmlDoc.ToString());
๐ Documentation
All documentation in this repository is proprietary and subject to the same terms as the software.
Getting Started
- CdaService Usage Guide - Complete guide to using the CdaService API
- Project Structure - Complete solution architecture and organization
- Document Type Configuration Guide - How to configure and use different C-CDA document types
ONC Certification & Compliance
- ONC Validation Guide - Step-by-step guide for ONC 170.315(b)(1) validation
- ONC Direct Protocol Compliance Guide - Sender/Receiver requirements and testing
- C-CDA Conformance Summary - Technical details of C-CDA 2.1 conformance implementation
Document Type Implementations
- Referral Note Implementation - Referral Note-specific implementation details and testing
HTML Rendering
- HTML Rendering Guide - Complete guide to rendering C-CDA documents as HTML
- CdaLib.Rendering README - HTML rendering library API reference
FHIR Integration
- FHIR Bundle Mapping - Guide to converting FHIR R4 bundles to C-CDA and CCD to FHIR
๐ฅ Supported Document Types
| Document Type | LOINC Code | Template ID | ONC ToC Compatible |
|---|---|---|---|
| Continuity of Care Document | 34133-9 | 2.16.840.1.113883.10.20.22.1.2 | โ |
| Discharge Summary | 18842-5 | 2.16.840.1.113883.10.20.22.1.1 | โ |
| Referral Note | 57133-1 | 2.16.840.1.113883.10.20.22.1.14 | โ |
| Transfer Summary | 18776-5 | 2.16.840.1.113883.10.20.22.1.1 | โ |
| History and Physical | 11488-4 | 2.16.840.1.113883.10.20.22.1.1 | โ |
| Progress Note | 11506-3 | 2.16.840.1.113883.10.20.22.1.1 | โ ๏ธ |
| Consultation Note | 11488-4 | 2.16.840.1.113883.10.20.22.1.1 | โ ๏ธ |
| Procedure Note | 28570-0 | 2.16.840.1.113883.10.20.22.1.1 | โ ๏ธ |
| Operative Note | 11506-3 | 2.16.840.1.113883.10.20.22.1.1 | โ ๏ธ |
| Emergency Department Note | 11488-4 | 2.16.840.1.113883.10.20.22.1.1 | โ ๏ธ |
๐ Validation System
Conformance Modes
CdaLib includes a sophisticated validation system with two conformance modes based on ONC Direct Protocol requirements:
Sender Conformance (ยง 170.202(d)) - Strict
For generating documents to send to other systems:
- Validates all required fields
- Checks document-type-specific required sections (Problems, Medications, Allergies for CCD)
- Ensures proper template IDs and document structure
- Validates header elements (patient, author, custodian)
- Used automatically in
service.Export()
Receiver Conformance (ยง 170.202(a)(2)) - Lenient
For parsing documents received from other systems:
- More tolerant of missing optional fields
- Focuses on structural integrity
- Allows parsing even with minor issues
- Tracks validation issues without rejecting documents
- Used automatically in
service.Import()
Example: Using Validation
using CdaLib;
using CdaLib.Validation;
using CdaLib.Parsing;
// Export with sender validation (strict)
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
var (exportErrors, xml) = service.Export(ccd);
if (exportErrors.Any())
{
Console.WriteLine("Document does not meet sender requirements:");
foreach (var error in exportErrors)
{
Console.WriteLine($" - [{error.ProblemType}] {error.Reason}");
}
}
// Import with receiver validation (lenient)
var (importErrors, parsedCcd) = service.Import("received-document.xml");
// Parser will extract data even if there are minor conformance issues
Console.WriteLine($"Parsed patient: {parsedCcd.Patient.FirstName} {parsedCcd.Patient.LastName}");
// Advanced: Use validator directly for custom validation
var conformanceErrors = CdaValidator.ValidateWithConformance(
xml,
ConformanceMode.Sender,
CcdaDocumentTypes.ContinuityOfCareDocument);
๐งช Testing Against ONC Validator
Sender Testing (Generate Documents)
- Generate a C-CDA document:
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
var (errors, xml) = service.Export(myCcdData);
xml.Save("my-document.xml");
- Upload
my-document.xmlto https://site.healthit.gov/c-cda/uscdi-v3 - Select Sender validation criteria
- Choose 170.315_b1_ToC_Amb scenario
- Verify all IG conformance and S&CC Reference validation passes
Receiver Testing (Parse Documents)
- Download scenario XML files from the ONC validator
- Parse them with CdaLib:
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
var (errors, ccd) = service.Import("scenario-file.xml");
- Verify data extraction is successful
- Upload scenario files to validator with Receiver criteria
๐ฆ Domain Model
The library uses a rich domain model for representing clinical data:
Core Components
- Ccd - Main document container
- Patient - Patient demographics and information
- Author - Document author information
- Custodian - Document custodian (organization)
Clinical Data
- Problems - Conditions and diagnoses
- Medications - Medication activities and prescriptions
- Allergies - Allergies and intolerances
- VitalSigns - Vital sign measurements
- Procedures - Procedures and interventions โญ NEW
- Immunizations - Vaccination history โญ NEW
- Results - Laboratory results
- Encounters - Healthcare encounters โญ NEW
- Goals - Patient goals โญ NEW
- SocialHistory - Social history including smoking status
USCDI V3 Extensions
- Goals - Patient goals
- HealthConcerns - Health concerns
- SDOH - Social Determinants of Health
- Notes - Clinical notes
- UDIs - Unique Device Identifiers
- Occupation - Occupational data
- TribalAffiliation - Tribal affiliation
- PregnancyObservations - Pregnancy status
- DisabilityStatus - Disability observations
- FunctionalStatus - Functional status
- Payer - Insurance payer information
- And more...
๐ง Advanced Features
FHIR Bundle Conversion (Bidirectional)
Convert between FHIR R4 bundles and C-CDA documents in both directions:
using CdaLib;
using Hl7.Fhir.Model; // Microsoft FHIR SDK
// Create a FHIR Bundle with patient data
var bundle = new Bundle
{
Entry = new List<Bundle.EntryComponent>
{
new Bundle.EntryComponent { Resource = new Patient { /* ... */ } },
new Bundle.EntryComponent { Resource = new AllergyIntolerance { /* ... */ } },
new Bundle.EntryComponent { Resource = new Condition { /* ... */ } },
new Bundle.EntryComponent { Resource = new MedicationStatement { /* ... */ } },
new Bundle.EntryComponent { Resource = new Procedure { /* ... */ } },
new Bundle.EntryComponent { Resource = new Immunization { /* ... */ } },
new Bundle.EntryComponent { Resource = new Encounter { /* ... */ } },
new Bundle.EntryComponent { Resource = new Observation { /* ... */ } },
new Bundle.EntryComponent { Resource = new DiagnosticReport { /* ... */ } },
new Bundle.EntryComponent { Resource = new Goal { /* ... */ } }
}
};
// Convert to C-CDA
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
var (errors, xmlDoc) = service.ExportFromFhir(bundle);
if (!errors.Any())
{
xmlDoc.Save("fhir-to-ccda.xml");
}
FHIR to C-CDA (FhirToCcdMapper):
- โ Patient
- โ AllergyIntolerance
- โ Condition
- โ MedicationStatement / MedicationRequest
- โ Procedure
- โ Immunization
- โ Encounter
- โ Observation (Results & Vital Signs)
- โ DiagnosticReport
- โ Goal
- โ Practitioner
- โ Organization
- โ CareTeam
C-CDA to FHIR (CcdToFhirMapper) โญ NEW:
- โ Patient โ FHIR Patient
- โ Allergies โ FHIR AllergyIntolerance
- โ Problems โ FHIR Condition
- โ Medications โ FHIR MedicationStatement
- โ Procedures โ FHIR Procedure
- โ Immunizations โ FHIR Immunization
- โ Encounters โ FHIR Encounter
- โ Results โ FHIR Observation (laboratory)
- โ Vital Signs โ FHIR Observation (vital-signs)
- โ Social History โ FHIR Observation (social-history)
- โ Goals โ FHIR Goal
- โ Care Team โ FHIR CareTeam
- โ Author โ FHIR Practitioner
- โ ProviderOrganization โ FHIR Organization
XML to HTML Rendering
Convert C-CDA XML directly to HTML without parsing:
using CdaLib.Rendering;
// From XML string
var xmlString = File.ReadAllText("document.xml");
var renderer = new CdaHtmlRenderer(CcdaDocumentTypes.ContinuityOfCareDocument);
var html = renderer.RenderXmlToHtml(xmlString);
File.WriteAllText("output.html", html);
// From XDocument
var xdoc = XDocument.Load("document.xml");
var html2 = renderer.RenderXmlToHtml(xdoc);
// ONC Style renderer also supports XML input
var oncRenderer = new OncStyleHtmlRenderer(CcdaDocumentTypes.ContinuityOfCareDocument);
var oncHtml = oncRenderer.RenderXmlToHtml(xmlString);
Multiple Document Types
Generate different document types for different use cases:
// Discharge Summary
var dischargeService = new CdaService(CcdaDocumentTypes.DischargeSummary);
var (errors1, dischargeXml) = dischargeService.Export(ccd);
// Referral Note
var referralService = new CdaService(CcdaDocumentTypes.ReferralNote);
var (errors2, referralXml) = referralService.Export(ccd);
// Transfer Summary
var transferService = new CdaService(CcdaDocumentTypes.TransferSummary);
var (errors3, transferXml) = transferService.Export(ccd);
Section Filtering โญ NEW
Control which sections are displayed when rendering CCDA documents to HTML. This feature allows you to selectively show only the sections you need in the HTML output, customizing the display according to user preferences.
By default, all sections are rendered (backward compatible behavior). Section filtering is optional and only applies when a SectionFilter is explicitly configured on the HTML renderer.
Exclusion Mode (Blacklist)
Exclude specific sections from HTML rendering while including all others:
using CdaLib.Rendering;
// Exclude specific sections from HTML rendering
var filter = new SectionFilter();
filter.Exclude(CdaSection.VitalSigns);
filter.Exclude(CdaSection.Results);
var renderer = new CdaHtmlRenderer(documentType);
renderer.SectionFilter = filter;
var html = renderer.RenderToHtml(ccd);
// HTML will not include VitalSigns and Results sections
Inclusion Mode (Whitelist)
Include only specific sections in HTML rendering, excluding all others:
using CdaLib.Rendering;
// Only include Problems, Medications, and Allergies in HTML
var whitelistFilter = new SectionFilter(new[] {
CdaSection.Problems,
CdaSection.Medications,
CdaSection.Allergies
});
var renderer = new CdaHtmlRenderer(documentType);
renderer.SectionFilter = whitelistFilter;
var html = renderer.RenderToHtml(ccd);
// HTML will only include Problems, Medications, and Allergies sections
Available Sections
The CdaSection enum provides type-safe section identifiers:
CdaSection.Problems- Problems and conditionsCdaSection.Medications- MedicationsCdaSection.Allergies- Allergies and intolerancesCdaSection.VitalSigns- Vital signsCdaSection.Results- Laboratory resultsCdaSection.Procedures- ProceduresCdaSection.Immunizations- ImmunizationsCdaSection.Encounters- EncountersCdaSection.PlanOfCare- Plan of careCdaSection.SocialHistory- Social historyCdaSection.FunctionalStatus- Functional statusCdaSection.Goals- GoalsCdaSection.HealthConcerns- Health concernsCdaSection.Notes- Clinical notes- And more... (see
CdaSectionenum for complete list)
Advanced Usage
using CdaLib.Rendering;
// Create filter with exclusion mode constructor
var exclusionFilter = new SectionFilter(
new[] { CdaSection.VitalSigns, CdaSection.Results },
isExclusionMode: true
);
// Dynamically modify filter
var filter = new SectionFilter();
filter.Exclude(CdaSection.VitalSigns);
filter.Include(CdaSection.Problems); // Switches to whitelist mode
filter.RemoveFromExclude(CdaSection.VitalSigns); // Remove from exclusion
filter.Clear(); // Reset to include all sections
// Check filter state
bool isWhitelist = filter.IsWhitelistMode;
var included = filter.IncludedSections;
var excluded = filter.ExcludedSections;
// Apply to renderer
var renderer = new CdaHtmlRenderer(documentType);
renderer.SectionFilter = filter;
var html = renderer.RenderToHtml(ccd);
Note: Section filtering is available in the CdaLib.Rendering package and uses semantic section names (CdaSection enum) rather than template IDs, providing a cleaner API that hides internal implementation details. Both CdaHtmlRenderer and OncStyleHtmlRenderer support section filtering.
Backward Compatibility
Static helper methods are available for quick operations:
// Quick compile without service
var xml = CcdCompiler.CompileStatic(ccd, CcdaDocumentTypes.ContinuityOfCareDocument);
// Quick parse without service
var parsedCcd = CcdaParser.ParseStatic(xml, CcdaDocumentTypes.ContinuityOfCareDocument);
Custom Validation
Use the validator directly for more control:
using CdaLib.Validation;
// XSD validation only
var xsdErrors = CdaValidator.Validate(xmlPath, ValidationMode.Strict);
// Full conformance validation
var allErrors = CdaValidator.ValidateWithConformance(
xmlDoc,
ConformanceMode.Sender,
CcdaDocumentTypes.ContinuityOfCareDocument
);
JSON Validation API โญ NEW
Validate C-CDA documents and get detailed results in JSON format with line numbers:
using CdaLib;
using System.IO;
var service = new CdaService(CcdaDocumentTypes.ContinuityOfCareDocument);
// Validate from file path
var jsonResult = service.Validate("document.xml");
// Returns JSON with errors, warnings, line numbers, and XPath
// Validate from FileInfo
var fileInfo = new FileInfo("document.xml");
var jsonResult2 = service.Validate(fileInfo);
// Validate from XML string
var xmlContent = File.ReadAllText("document.xml");
var jsonResult3 = service.Validate(xmlContent);
// Example JSON response:
// {
// "status": "error",
// "message": "Validation found 2 error(s) and 3 warning(s)",
// "fileName": "document.xml",
// "errors": [
// {
// "lineNumber": 45,
// "fieldName": "patient.name",
// "importance": "Required",
// "message": "Patient name is required",
// "xPath": "/ClinicalDocument/recordTarget/patientRole/patient/name"
// }
// ],
// "warnings": [
// {
// "lineNumber": 120,
// "fieldName": "medication.dose",
// "importance": "Recommended",
// "message": "Medication dose is recommended",
// "xPath": "/ClinicalDocument/component/structuredBody/component/section/entry/substanceAdministration/doseQuantity"
// }
// ]
// }
๐๏ธ Architecture
Key Components
CdaService- Primary user-facing APICcdCompiler- Compiles domain models to C-CDA XMLCcdaParser- Parses C-CDA XML to domain modelsCdaValidator- XSD and conformance validationConformanceValidator- ONC sender/receiver conformanceCcdaDocumentTypes- Document type definitions
Design Principles
- Type Safety - Document types are strongly typed
- Explicit Configuration - No hidden defaults, clear intent
- Separation of Concerns - Parsing, compilation, and validation are distinct
- Standards Compliance - Follows C-CDA 2.1 and ONC requirements
- Flexibility - Support for both instance-based and static usage
๐งช Testing
The library includes comprehensive tests:
# Run all tests
dotnet test
# Run specific test categories
dotnet test --filter "FullyQualifiedName~OncTransitionOfCareTests"
dotnet test --filter "FullyQualifiedName~CcdCompilerTests"
dotnet test --filter "FullyQualifiedName~CdaServiceTests"
Code coverage
Code coverage is collected for CdaLib and CdaLib.Rendering using Coverlet. Coverage is restricted to these two assemblies (test projects are excluded).
Run tests with coverage locally:
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults --settings coverlet.runsettings
Coverage files (Cobertura XML) are written under TestResults per test project. To generate a merged HTML report locally, install ReportGenerator and run:
dotnet tool install -g dotnet-reportgenerator-globaltool
reportgenerator -reports:"**/TestResults/**/coverage.cobertura.xml" -targetdir:./coveragereport -reporttypes:Html;TextSummary
Open coveragereport/index.html to view the report. In CI, coverage is collected the same way and the HTML report is uploaded as an artifact.
Test Categories
- OncTransitionOfCareTests - ONC 170.315(b)(1) scenario tests
- CcdCompilerTests - Compiler functionality and roundtrip tests
- CcdaParserTests - Parser functionality tests
- CdaServiceTests - Service workflow tests
- DocumentTypeTests - Document type configuration tests
- SenderConformanceTests - Sender conformance validation
- ReceiverConformanceTests - Receiver conformance validation
๐ Additional Resources
Standards References
Online Tools
- ONC C-CDA Validator - Official validator
- C-CDA Scorecard - Document quality assessment
๐ค Contributing
When contributing, ensure:
- All tests pass (
dotnet test) - Code follows existing patterns
- Document any new features
- Validate against ONC online validator
๐ License
[Add your license information here]
๐ Support
For issues or questions:
- Check the documentation guides above
- Review test examples in
CdaLib.Tests/ - Validate with the ONC online validator
- Open an issue with specific error messages
Version: 1.21.0
Target Framework: .NET 8.0, .NET 9.0
C-CDA Version: 2.1
USCDI Version: V3
ONC Certification: 170.315(b)(1) Transitions of Care
NuGet Packages:
CdaLib(1.21.0) - Core libraryCdaLib.Rendering(1.21.0) - HTML rendering (depends on CdaLib 1.21.0)
FHIR (CdaLib): CdaLib depends on Hl7.Fhir.R4 5.12.2 (FHIR R4). This version is compatible with .NET 8 and .NET 9 and is aligned with common EHR integrations (e.g. ThyraEHR). The 5.12.x line is backward compatible; upgrading from 5.0.x is supported.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Hl7.Fhir.R4 (>= 5.12.2)
-
net9.0
- Hl7.Fhir.R4 (>= 5.12.2)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on CdaLib:
| Package | Downloads |
|---|---|
|
CdaLib.Rendering
HTML rendering helpers for CdaLib, including ONC-style validator HTML and a modern Bootstrap-based renderer for C-CDA documents. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.21.0 | 117 | 2/27/2026 |
| 1.20.0 | 116 | 2/24/2026 |
| 1.19.0 | 115 | 2/23/2026 |
| 1.18.0 | 147 | 2/9/2026 |
| 1.17.0 | 122 | 2/3/2026 |
| 1.16.0 | 126 | 1/30/2026 |
| 1.15.0 | 118 | 1/27/2026 |
| 1.14.0 | 120 | 1/21/2026 |
| 1.13.0 | 114 | 1/21/2026 |
| 1.12.0 | 491 | 1/20/2026 |
| 1.11.0 | 123 | 1/18/2026 |
| 1.10.0 | 125 | 1/15/2026 |
| 1.9.0 | 129 | 1/14/2026 |
| 1.8.0 | 118 | 1/14/2026 |
| 1.7.0 | 115 | 1/14/2026 |
| 1.6.0 | 120 | 1/13/2026 |
| 1.5.0 | 121 | 1/13/2026 |
| 1.4.0 | 129 | 1/8/2026 |
| 1.3.0 | 123 | 1/7/2026 |
| 1.2.0 | 119 | 1/7/2026 |
See CHANGELOG.md for release notes