How to Convert DICOM to XML and Back using DicomXmlSerializer
This tutorial demonstrates how to convert DICOM files to XML format and deserialize XML back to DICOM using C#. XML format is preferred for integration with legacy systems, HL7 workflows, and environments where XML tooling is well-established.
When to Use XML over JSON
- Legacy Integration:
- Existing middleware and systems often expect XML format.
- HL7 Compatibility:
- Healthcare systems using HL7 v2/v3 typically work with XML.
- XML Tooling:
- Organizations with established XSLT transforms and XPath queries.
- Schema Validation:
- XML schemas provide strict validation capabilities.
Prerequisites: Preparing the Environment
- Set up Visual Studio or any compatible .NET IDE.
- Create a new .NET 8 console application project.
- Install Aspose.Medical from the NuGet Package Manager.
Step-by-Step Guide to Convert DICOM to XML
Step 1: Install Aspose.Medical
Add the Aspose.Medical library to your project using NuGet.
Install-Package Aspose.MedicalStep 2: Include Necessary Namespaces
Add references to the required namespaces in your code.
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;Step 3: Load the DICOM File
Load the DICOM file you want to convert.
DicomFile dcm = DicomFile.Open("patient_scan.dcm");Step 4: Serialize to XML
Use the DicomXmlSerializer.Serialize method to convert to XML.
string xml = DicomXmlSerializer.Serialize(dcm.Dataset);Step 5: Save the XML Output
Save the XML to a file for storage or transmission.
File.WriteAllText("patient_scan.xml", xml);Step 6: Deserialize XML Back to Dataset
To convert XML back to DICOM, use the Deserialize method.
Dataset? dataset = DicomXmlSerializer.Deserialize(xml);Complete Code Example: DICOM to XML Conversion
Here is a complete example for converting DICOM to XML:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Load DICOM file
DicomFile dcm = DicomFile.Open("patient_scan.dcm");
// Convert to XML
string xml = DicomXmlSerializer.Serialize(dcm.Dataset);
// Save to file
File.WriteAllText("patient_scan.xml", xml);
Console.WriteLine("DICOM converted to XML successfully!");
Console.WriteLine($"Output saved to: patient_scan.xml");Complete Code Example: XML to DICOM Conversion
Here is a complete example for converting XML back to DICOM:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Read XML from file
string xml = File.ReadAllText("patient_scan.xml");
// Deserialize to Dataset
Dataset? dataset = DicomXmlSerializer.Deserialize(xml);
if (dataset != null)
{
// Create DicomFile from Dataset
DicomFile dcm = new DicomFile(dataset);
// Save as DICOM file
dcm.Save("reconstructed.dcm");
Console.WriteLine("XML converted back to DICOM successfully!");
}
else
{
Console.WriteLine("Failed to deserialize XML.");
}Round-Trip Example: DICOM → XML → DICOM
Complete round-trip conversion demonstrating data integrity:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Load original DICOM file
DicomFile original = DicomFile.Open("original_scan.dcm");
Console.WriteLine("Original DICOM loaded.");
// Convert to XML
string xml = DicomXmlSerializer.Serialize(original.Dataset);
Console.WriteLine($"Converted to XML ({xml.Length} characters).");
// Save XML (for transmission or storage)
File.WriteAllText("intermediate.xml", xml);
// Later: Deserialize XML back to Dataset
string loadedXml = File.ReadAllText("intermediate.xml");
Dataset? reconstructedDataset = DicomXmlSerializer.Deserialize(loadedXml);
if (reconstructedDataset != null)
{
// Create new DicomFile
DicomFile reconstructed = new DicomFile(reconstructedDataset);
reconstructed.Save("reconstructed_scan.dcm");
Console.WriteLine("Round-trip complete: DICOM → XML → DICOM");
}Example XML Output Structure
The XML output represents DICOM tags in a structured format:
<?xml version="1.0" encoding="utf-8"?>
<NativeDicomModel>
<DicomAttribute tag="00080005" vr="CS" keyword="SpecificCharacterSet">
<Value number="1">ISO_IR 100</Value>
</DicomAttribute>
<DicomAttribute tag="00080020" vr="DA" keyword="StudyDate">
<Value number="1">20240115</Value>
</DicomAttribute>
<DicomAttribute tag="00100010" vr="PN" keyword="PatientName">
<PersonName number="1">
<Alphabetic>
<FamilyName>DOE</FamilyName>
<GivenName>JOHN</GivenName>
</Alphabetic>
</PersonName>
</DicomAttribute>
<DicomAttribute tag="00100020" vr="LO" keyword="PatientID">
<Value number="1">12345</Value>
</DicomAttribute>
</NativeDicomModel>Comparing JSON vs XML Output
Size Comparison
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
DicomFile dcm = DicomFile.Open("sample.dcm");
string json = DicomJsonSerializer.Serialize(dcm);
string xml = DicomXmlSerializer.Serialize(dcm.Dataset);
Console.WriteLine($"JSON size: {json.Length:N0} characters");
Console.WriteLine($"XML size: {xml.Length:N0} characters");
// XML is typically 20-40% larger than JSONUse Case Recommendations
| Scenario | Recommended Format |
|---|---|
| New web services | JSON |
| Legacy PACS integration | XML |
| HL7 middleware | XML |
| JavaScript frontends | JSON |
| XSLT transformations | XML |
| NoSQL databases | JSON |
| Schema validation | XML |
Integration with Legacy Systems
Example integration with legacy middleware:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
using System.Net.Http;
using System.Text;
DicomFile dcm = DicomFile.Open("patient_scan.dcm");
string xml = DicomXmlSerializer.Serialize(dcm.Dataset);
// Send to legacy SOAP service
using HttpClient client = new();
var content = new StringContent(xml, Encoding.UTF8, "application/xml");
HttpResponseMessage response = await client.PostAsync(
"http://legacy-pacs/dicom/import",
content
);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("XML successfully sent to legacy system!");
}Troubleshooting
Handling Invalid XML
Wrap deserialization in try-catch for error handling:
try
{
Dataset? dataset = DicomXmlSerializer.Deserialize(xml);
if (dataset == null)
{
Console.WriteLine("Deserialization returned null.");
}
}
catch (System.Xml.XmlException ex)
{
Console.WriteLine($"XML parsing error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Deserialization error: {ex.Message}");
}Character Encoding Issues
Ensure proper encoding when reading/writing XML files:
// Write with explicit encoding
using (StreamWriter writer = new StreamWriter("output.xml", false, Encoding.UTF8))
{
writer.Write(xml);
}
// Read with explicit encoding
using (StreamReader reader = new StreamReader("input.xml", Encoding.UTF8))
{
string xml = reader.ReadToEnd();
}Large File Handling
For very large DICOM files, consider streaming:
using (FileStream fs = File.Create("large_output.xml"))
using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
{
string xml = DicomXmlSerializer.Serialize(dcm.Dataset);
writer.Write(xml);
}Additional Information
- XML format provides better human readability with proper indentation.
- XML is more verbose than JSON, resulting in larger file sizes.
- Consider compression for storing or transmitting large XML files.
- Both JSON and XML support the same DICOM data types and structures.
Conclusion
This tutorial has demonstrated how to convert DICOM files to XML format and deserialize XML back to DICOM in C# using Aspose.Medical. XML serialization is essential for integrating with legacy healthcare systems and environments that rely on XML tooling and workflows.