C-CDA R2.1 + Companion Guide R4.1

Legacy EHR, Modern Export

Generate valid C-CDA R2.1 XML documents from any ChartScribe note. Full LOINC-coded sections, structured vital sign entries, digital signatures, and legacy EHR compatibility — all via Jinja2 templates.

Architecture

From Note to C-CDA XML

Jinja2 templating engine generates schema-valid C-CDA R2.1 from internal data. Trigger on button click or scheduled batch.

ChartScribe DB

Internal note storage

Jinja2 Engine

LOINC-coded templates

C-CDA R2.1 XML

Schema-valid output

NIST Validate

Schema + schematron

Legacy EHR

EMIS / SystmOne / Cerner

Backend

Python + Jinja2

Templating engine with lxml schema validation

Standard

C-CDA R2.1

Companion Guide R4.1 — 2026 standard compliance

Storage

legacy_exports table

Audit trail for every generated document

Enterprise

Batch Export

Scheduled or on-demand bulk generation

Complete Mapping

Internal Data → C-CDA XML Sections

Every ChartScribe field maps to a specific C-CDA section with LOINC coding.

ChartScribe FieldC-CDA Section / ElementLOINCRequiredExample
Note IDClinicalDocument.id / setId—RequiredUUID v4: 550e8400-e29b-41d4-a716-446655440000
Patient DemographicsrecordTarget / patientRole / patient—RequiredName, DOB, gender, MRN
Clinician (Author)author / assignedAuthor / assignedPerson—RequiredDr. Jane Smith, NPI: 1234567890
Encounter DatedocumentationOf / serviceEvent / effectiveTime—Required20260620T143000+0000 (start & end)
Subjective (HPI)component / section (History of Present Illness)10164-2Required<text>Patient reports chest pain for 2 days...</text>
Objective (Vitals)component / section (Vital Signs)8716-3Required<entry><organizer> BP, HR, SpO2 as observation entries </organizer></entry>
Assessmentcomponent / section (Assessment)51848-6Must Support<text>1. Unstable angina (I20.0)</text>
Problem Listcomponent / section (Problem List)11450-4Required<entry><observation classCode="COND">...</observation></entry>
Plan of Carecomponent / section (Plan of Care)18776-5Required<entry><planOfCareActivity><text>Start lisinopril 10mg</text></planOfCareActivity></entry>
Medicationscomponent / section (Medications)10160-0Required<entry><substanceAdministration>...</substanceAdministration></entry>
Allergiescomponent / section (Allergies)48765-2Required<entry><observation classCode="OBS" moodCode="EVN">...</observation></entry>
Digital Signatureauthenticator / legalAuthenticator—Required<time value="20260620T143000+0000"/><signatureCode code="S"/>
Care Remindercomponent / section (custom extension)customOptionalPatient follow-up flag via chartscribe.care
Section Profiles

10 C-CDA LOINC-Coded Sections

Each section follows its HL7 template ID with full narrative + structured entry support.

Implementation

Ready-to-Run Python Code

Jinja2 templating engine with full C-CDA R2.1 structure.

jinja2
from jinja2 import Environment, BaseLoader
from datetime import datetime
import uuid

# ── Jinja2 Environment ──
env = Environment(loader=BaseLoader(), autoescape=False)

CCDA_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">
  <realmCode code="US"/>
  <typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>
  <templateId root="2.16.840.1.113883.10.20.22.1.1"/>  <!-- CCD template -->
  <templateId root="2.16.840.1.113883.10.20.22.1.4" extension="2023-05-01"/>  <!-- CCD R2.1 -->
  <id root="{{ note.uuid }}"/>
  <code code="11488-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Consultation note"/>
  <title>Consultation Note - {{ note.patient_name }}</title>
  <effectiveTime value="{{ note.encounter_date }}"/>
  <confidentialityCode code="N" codeSystem="2.16.840.1.113883.5.25" displayName="Normal"/>
  <languageCode code="en-US"/>

  <!-- Patient -->
  <recordTarget>
    <patientRole>
      <id root="2.16.840.1.113883.4.1" extension="{{ note.patient_mrn }}"/>  <!-- SSN placeholder for MRN -->
      <addr use="HP"><streetAddressLine>Unknown</streetAddressLine><city>Unknown</city><state>UNK</state></addr>
      <patient>
        <name use="L"><given>{{ note.patient_first }}</given><family>{{ note.patient_last }}</family></name>
        <administrativeGenderCode code="{{ note.gender_code }}" codeSystem="2.16.840.1.113883.5.1"/>
        <birthTime value="{{ note.dob }}"/>
      </patient>
    </patientRole>
  </recordTarget>

  <!-- Author (Clinician) -->
  <author>
    <time value="{{ note.authored_time }}"/>
    <assignedAuthor>
      <id root="2.16.840.1.113883.4.6" extension="{{ note.clinician_npi }}"/>  <!-- NPI -->
      <assignedPerson>
        <name><prefix>Dr.</prefix><given>{{ note.clinician_first }}</given><family>{{ note.clinician_last }}</family></name>
      </assignedPerson>
      <representedOrganization>
        <name>{{ note.organization_name }}</name>
      </representedOrganization>
    </assignedAuthor>
  </author>

  <!-- Authenticator (Digital Signature) -->
  <authenticator>
    <time value="{{ note.signed_time }}"/>
    <signatureCode code="S"/>
    <assignedEntity>
      <id root="2.16.840.1.113883.4.6" extension="{{ note.clinician_npi }}"/>
      <assignedPerson>
        <name><prefix>Dr.</prefix><given>{{ note.clinician_first }}</given><family>{{ note.clinician_last }}</family></name>
      </assignedPerson>
    </assignedEntity>
  </authenticator>

  <!-- Encounter -->
  <documentationOf>
    <serviceEvent classCode="PCPR">
      <effectiveTime>
        <low value="{{ note.encounter_start }}"/>
        <high value="{{ note.encounter_end }}"/>
      </effectiveTime>
    </serviceEvent>
  </documentationOf>

  <!-- Body -->
  <component>
    <structuredBody>

      <!-- Subjective: History of Present Illness -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.17"/>
          <code code="10164-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="History of Present Illness"/>
          <title>History of Present Illness</title>
          <text><paragraph>{{ note.subjective }}</paragraph></text>
        </section>
      </component>

      <!-- Objective: Vital Signs -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.4.1"/>
          <code code="8716-3" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Vital Signs"/>
          <title>Vital Signs</title>
          <text>
            <table><thead><tr><th>Vital</th><th>Value</th></tr></thead>
            <tbody>
              {% for vital in note.vitals %}
              <tr><td>{{ vital.name }}</td><td>{{ vital.value }} {{ vital.unit }}</td></tr>
              {% endfor %}
            </tbody></table>
          </text>
          {% for vital in note.vitals %}
          <entry typeCode="DRIV">
            <organizer classCode="CLUSTER" moodCode="EVN">
              <templateId root="2.16.840.1.113883.10.20.22.4.26"/>
              <statusCode code="completed"/>
              <effectiveTime value="{{ note.encounter_date }}"/>
              <component><observation classCode="OBS" moodCode="EVN">
                <templateId root="2.16.840.1.113883.10.20.22.4.27"/>
                <code code="{{ vital.loinc }}" codeSystem="2.16.840.1.113883.6.1" displayName="{{ vital.name }}"/>
                <value xsi:type="PQ" value="{{ vital.value }}" unit="{{ vital.ucum_unit }}"/>
              </observation></component>
            </organizer>
          </entry>
          {% endfor %}
        </section>
      </component>

      <!-- Assessment -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.8"/>
          <code code="51848-6" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Assessment"/>
          <title>Assessment</title>
          <text><paragraph>{{ note.assessment }}</paragraph></text>
          {% for dx in note.diagnoses %}
          <entry typeCode="DRIV">
            <act classCode="ACT" moodCode="EVN">
              <templateId root="2.16.840.1.113883.10.20.22.4.3"/>
              <entryRelationship typeCode="SUBJ">
                <observation classCode="OBS" moodCode="EVN">
                  <code code="29308-4" codeSystem="2.16.840.1.113883.6.1"/>
                  <value xsi:type="CD" code="{{ dx.icd10 }}" codeSystem="2.16.840.1.113883.6.90" displayName="{{ dx.description }}"/>
                </observation>
              </entryRelationship>
            </act>
          </entry>
          {% endfor %}
        </section>
      </component>

      <!-- Plan of Care -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.10"/>
          <code code="18776-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Plan of Care"/>
          <title>Plan of Care</title>
          <text><paragraph>{{ note.plan }}</paragraph></text>
        </section>
      </component>

      <!-- Medications -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.1.1"/>
          <code code="10160-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Medications"/>
          <title>Medications</title>
          <text><paragraph>{{ note.medications_text }}</paragraph></text>
        </section>
      </component>

      <!-- ChartScribe.care Reminder (Custom Extension) -->
      {% if note.care_reminder %}
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.17"/>
          <code code="note" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Additional Note"/>
          <title>Patient Follow-Up (ChartScribe.care)</title>
          <text><paragraph>{{ note.care_reminder }}</paragraph></text>
        </section>
      </component>
      {% endif %}

    </structuredBody>
  </component>
</ClinicalDocument>'''


def generate_ccda(note: dict) -> str:
    """Generate a C-CDA R2.1 XML document from a ChartScribe note."""
    template = env.from_string(CCDA_TEMPLATE)

    context = {
        "note": {
            **note,
            "uuid": str(uuid.uuid4()),
            "authored_time": datetime.utcnow().strftime("%Y%m%d%H%M%S+0000"),
            "signed_time": datetime.utcnow().strftime("%Y%m%d%H%M%S+0000"),
            "gender_code": note.get("gender", "U")[0].upper(),  # M / F / U
            "organization_name": note.get("organization", "ChartScribe Healthcare"),
        }
    }

    xml_output = template.render(**context)

    # ── Schema Validation (optional but recommended) ──
    # from lxml import etree
    # schema = etree.XMLSchema(etree.parse("CDA.xsd"))
    # schema.assertValid(etree.fromstring(xml_output.encode()))

    return xml_output


def save_ccda(note_id: str, xml: str) -> str:
    """Save C-CDA to legacy_exports table and return download path."""
    filepath = f"/exports/ccda/note-{note_id}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xml"
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(xml)
    # TODO: Insert into legacy_exports table with audit metadata
    return filepath

LOINC-coded sections

Schema validation ready

Batch + single export

Digital signature support

API Reference

Endpoints to Implement

Three core endpoints for C-CDA generation: single export, preview, and batch.

POST/export-ccda/{note_id}

Generate and download a single C-CDA XML document. Returns FileResponse with application/xml MIME type.

Header: x-patient-consent: granted

FileResponse → chartscribe-note-{id}.xml
GET/export-ccda/preview/{note_id}

Return C-CDA XML as inline preview for the doctor dashboard UI. No consent check required for preview.

PlainTextResponse → inline XML preview
POST/export-ccda/batch

Enterprise batch export. Queues in background, returns job ID for status polling.

Header: x-patient-consent: granted + Body: [note_ids]

{ status: "queued", job_id, total_notes, check_status_url }
Quality Assurance

Testing & Validation Checklist

Before going live, every C-CDA document must pass these four gates.

Gate 1

NIST Validator

Run the official NIST C-CDA validator against generated XML. Pass both schema validation (XSD) and schematron assertion checks.

Gate 2

Legacy EHR Import

Test import into EMIS (legacy), older SystmOne instances, and Cerner PowerChart. Verify all sections render correctly.

Gate 3

Document Templates

Verify against document-level templates: CCD (2.16.840.1.113883.10.20.22.1.1), Progress Note, and Consultation Note (11488-4).

Gate 4

Schema + Readability

Ensure XML is schema-valid (CDA.xsd) and human-readable when opened in a browser or XML viewer without transformation.

Need legacy EHR export?

Our team will configure C-CDA export for your specific legacy system. NIST-validated documents, delivered within 48 hours.

We use cookies to improve your experience

Necessary cookies are always active. Analytics and marketing cookies help us improve ChartScribe and show relevant content. You can manage your preferences at any time.

We use cookies to improve your experience

Necessary cookies are always active. Analytics and marketing cookies help us improve ChartScribe and show relevant content. You can manage your preferences at any time.