How to Validate Documents Against OpenXML Schema Before Delivery
OfficeCLI validates Word, Excel, and PowerPoint documents against OpenXML schemas using the Open XML SDK's OpenXmlValidator encapsulated in the RawXmlHelper.ValidateDocument method, ensuring strict schema compliance before delivery without modifying the file contents.
Delivering Office documents that conform to the OpenXML specification prevents compatibility issues across Microsoft Office versions. The iOfficeAI/OfficeCLI repository provides a robust validation pipeline that checks Word, Excel, and PowerPoint files against official schemas using the Open XML SDK. This validation executes in read-only mode, guaranteeing that pre-delivery integrity checks never mutate document content.
Architectural Overview of OpenXML Validation
The validation architecture centers on a unified helper that encapsulates the Open XML SDK's validation logic. When invoked, the system performs four distinct operations: opening the package with the appropriate SDK document type (WordprocessingDocument, SpreadsheetDocument, or PresentationDocument), instantiating an OpenXmlValidator, traversing the entire document tree to collect validation errors, and wrapping each SDK ValidationError in OfficeCLI's own error type for consistent reporting.
This design delegates the heavy lifting to RawXmlHelper.cs, while specific handlers for each Office application format the results for their respective contexts. The validation occurs before any mutation operations, making it safe to run on production documents intended for client delivery.
Core Validation Implementation
The RawXmlHelper.ValidateDocument method serves as the single entry point for schema validation across all document types. This method accepts an OpenXmlDocument instance and file path, then creates an OpenXmlValidator instance that validates against the specific FileFormatVersions of the document.
The validator traverses the document tree recursively, checking each element against the OpenXML schema definitions. Errors captured during this traversal include schema violations, incorrect element ordering, and attribute value constraints. Each raw SDK error is wrapped in a ValidationError object containing the description, part URI, and element location, enabling precise debugging of schema issues.
Document-Specific Handler Delegation
While RawXmlHelper contains the generic logic, individual handlers implement document-type-specific validation entry points that delegate to the core helper.
Word Document Validation
The Word handler exposes a Validate method that opens the WordprocessingDocument and forwards the request to RawXmlHelper. According to the source implementation in WordHandler.cs, this handler manages the document lifecycle and ensures proper disposal of resources after validation completes.
Excel Workbook Validation
For spreadsheet files, the Excel handler follows an identical pattern, calling RawXmlHelper.ValidateDocument with a SpreadsheetDocument instance. The implementation in ExcelHandler.cs handles Excel-specific package structures while reusing the shared validation engine.
PowerPoint Presentation Validation
Presentation files undergo the same validation flow through the PowerPoint handler. As shown in PowerPointHandler.cs, this handler manages PresentationDocument instances and returns the validation error collection for consumer processing.
Command-Line Integration and Exit Codes
The validation functionality exposes itself through the CLI via the ResidentServer command dispatcher. When users invoke the validate verb, ResidentServer.cs routes the request to the appropriate handler based on file extension, executes the validation, and prints formatted error messages to stderr.
If validation detects any schema violations, the process exits with status code 1, enabling straightforward integration into automated build pipelines. A successful validation returns exit code 0, signaling that the document conforms to the OpenXML specification and is safe for delivery.
Practical Code Examples
C# Library Usage
Validate documents programmatically using the OfficeCLI core library directly:
using DocumentFormat.OpenXml.Packaging;
using OfficeCli.Core;
// Open a Word document read-only and validate against OpenXML schema
using var wordDoc = WordprocessingDocument.Open(@"C:\Docs\Report.docx", false);
var errors = RawXmlHelper.ValidateDocument(wordDoc, @"C:\Docs\Report.docx");
if (errors.Count == 0)
{
Console.WriteLine("Document conforms to OpenXML schema.");
}
else
{
Console.WriteLine($"Found {errors.Count} validation error(s):");
foreach (var err in errors)
{
Console.WriteLine($"- {err.Description} (Part: {err.PartUri})");
}
}
This example references the RawXmlHelper.ValidateDocument implementation that wraps the OpenXmlValidator functionality.
Command Line Validation
Execute validation directly from the terminal to verify documents before delivery:
# Validate Word document against OpenXML schema
officecli validate path/to/document.docx
# Validate Excel workbook
officecli validate path/to/workbook.xlsx
# Validate PowerPoint presentation
officecli validate path/to/presentation.pptx
The CLI outputs each validation error with its location and description, returning a non-zero exit code if schema violations exist.
Python Wrapper Integration
For Python environments, the OfficeCLI wrapper exposes the same validation capabilities:
import officecli
# Validate document against OpenXML schema
errors = officecli.validate('documents/report.docx')
if errors:
print(f"Validation failed with {len(errors)} errors:")
for e in errors:
print(f"- {e['description']} (part: {e['part']})")
else:
print("Document is valid for delivery.")
The Python wrapper calls the underlying C# validation routine and returns structured error dictionaries that mirror the ValidationError properties.
Summary
- RawXmlHelper.ValidateDocument in RawXmlHelper.cs serves as the central validation engine using the Open XML SDK's OpenXmlValidator.
- Document-specific handlers in WordHandler.cs, ExcelHandler.cs, and PowerPointHandler.cs delegate to the core helper while managing format-specific package types.
- Validation operates in read-only mode, ensuring documents remain unmodified during schema verification.
- The ResidentServer.cs dispatcher provides CLI access with non-zero exit codes for failed validations, supporting CI/CD integration.
- Errors include precise location data (part URI and element path) enabling rapid correction of schema violations before delivery.
Frequently Asked Questions
What is OpenXML schema validation and why does it matter for document delivery?
OpenXML schema validation verifies that a document's XML structure conforms to the standardized schemas defined by the OpenXML specification (ISO/IEC 29500). Validating documents before delivery ensures compatibility across Microsoft Office versions and prevents corruption warnings when end users open files, maintaining professional document integrity.
How does OfficeCLI handle validation errors?
OfficeCLI captures raw validation errors from the OpenXmlValidator and wraps them in ValidationError objects containing the error description, part URI, and XML element location. These structured errors are returned programmatically or printed to the console when using the CLI, providing actionable details for fixing schema violations.
Can validation be integrated into CI/CD pipelines?
Yes. The OfficeCLI validate command returns exit code 1 when schema violations are detected and exit code 0 for valid documents. This behavior allows build servers to fail deployments automatically when documents do not conform to OpenXML standards, preventing invalid files from reaching production environments.
Does validating a document modify its contents?
No. The validation process opens documents in read-only mode using the Open XML SDK. The RawXmlHelper.ValidateDocument method only inspects the document structure and never writes changes back to the file, making it safe to run on final documents intended for immediate delivery.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →