How to Validate Document Integrity Against OpenXML Schemas Using OfficeCLI
The officecli validate command checks Word, Excel, and PowerPoint documents against official OpenXML schemas, returning exit code 0 for compliant files and exit code 1 for structural violations, with support for machine-readable JSON output.
The iOfficeAI/OfficeCLI toolkit provides a robust command-line interface for automating Microsoft Office document workflows. When you need to ensure that your .docx, .xlsx, or .pptx files adhere strictly to the OpenXML specification, the validate command serves as a critical quality gate in development and publishing pipelines.
Understanding the Validation Pipeline
The officecli validate command executes a multi-stage pipeline that leverages the Open XML SDK to verify document structure. According to the iOfficeAI/OfficeCLI source code, this process combines command-line parsing, intelligent document handling, and schema validation.
Command Construction and Argument Parsing
The validation entry point is defined in src/officecli/CommandBuilder.Check.cs. This module constructs the command verb, adds the required <file> argument, and registers the global --json option (lines 12-20):
// CommandBuilder.Check.cs defines the validate command structure
command.AddArgument(new Argument<FileInfo>("file"));
command.AddOption(new Option<bool>("--json"));
command.SetHandler((file, json) => {
// Validation orchestration logic
});
Document Handler Resolution
Once invoked, the system resolves the appropriate handler for the target file format. The DocumentHandlerFactory.Open method in src/officecli/Handlers/DocumentHandlerFactory.cs instantiates format-specific handlers—such as WordHandler, PowerPointHandler, or ExcelHandler—based on the file extension.
Schema Validation Implementation
Each handler implements a Validate() method that invokes the Open XML SDK's validator. For Word documents, the implementation resides in src/officecli/Handlers/Word/WordHandler.cs. This method traverses the document's OpenXML parts, collects ValidationError objects, and returns them for reporting:
- Validates against official OpenXML schemas
- Detects invalid tags, missing required elements, and structural anomalies
- Returns a comprehensive list of validation errors
Resident Mode Optimization
If a resident server is already processing the document, ResidentServer.cs (lines 22-27) forwards the validation request to the existing instance. This optimization prevents redundant document opening and improves performance in batch operations.
Output Formats and Exit Codes
The command supports two output modes controlled by the --json flag, with distinct exit code semantics that enable CI/CD integration.
Human-Readable Output (Default)
Without the --json flag, the command writes validation results to standard output and errors to standard error (stderr). A valid document produces:
officecli validate report.docx
#> Validation passed: no errors found.
Documents containing schema violations output error details to stderr (as implemented in lines 47-57 of the command builder), allowing pipelines to separate diagnostics from standard output.
JSON Envelope Mode
When --json is specified, the FormatValidationErrors method in src/officecli/CommandBuilder.cs (lines 18-34) serializes errors into a structured format wrapped by OutputFormatter.WrapEnvelope:
officecli validate --json report.docx
The resulting JSON includes error types, descriptions, and file paths:
{
"success": false,
"count": 2,
"errors": [
{
"type": "InvalidTag",
"description": "Unexpected element <w:tbl>",
"path": "word/document.xml"
},
{
"type": "MissingRequired",
"description": "Required child <w:p> missing",
"part": "word/document.xml"
}
]
}
Exit Code Semantics
The command returns 0 when validation passes and 1 when any schema errors are detected (line 60). This binary result enables shell scripting patterns:
officecli validate contract.docx && echo "Schema compliant" || echo "Validation failed"
Practical Usage Examples
Basic Validation Check
Validate a single document with human-readable feedback:
officecli validate presentation.pptx
JSON Output for Scripting
Parse validation errors with jq or other JSON processors:
officecli validate --json spreadsheet.xlsx | jq '.errors[] | .description'
Conditional CI Pipeline Gates
Use the exit code to control build flow:
if officecli validate --json contract.docx; then
echo "Document is schema-compliant"
exit 0
else
echo "Document has schema errors – see output above"
exit 1
fi
Summary
- The
officecli validatecommand in iOfficeAI/OfficeCLI performs OpenXML schema validation on Word, Excel, and PowerPoint documents. - CommandBuilder.Check.cs defines the command interface, while DocumentHandlerFactory.cs routes files to format-specific handlers like WordHandler.cs.
- The validator returns exit code 0 for compliant documents and exit code 1 for schema violations.
- Use the
--jsonflag to enable machine-readable output suitable for automated parsing in CI/CD systems. - Resident mode support in ResidentServer.cs optimizes performance when processing multiple operations on the same document.
Frequently Asked Questions
What file formats does OfficeCLI validate support?
OfficeCLI validates all major OpenXML formats including Word documents (.docx), Excel spreadsheets (.xlsx), and PowerPoint presentations (.pptx). The DocumentHandlerFactory automatically selects the appropriate handler based on file extension.
How does OfficeCLI handle validation errors?
The command collects ValidationError objects from the Open XML SDK validator, categorizing issues by type (such as InvalidTag or MissingRequired). In human-readable mode, errors write to stderr; in JSON mode, they serialize via FormatValidationErrors in CommandBuilder.cs with full path and description metadata.
Can I use OfficeCLI validate in a GitHub Actions workflow?
Yes. The binary exit codes (0 for success, 1 for failure) and JSON output make it ideal for CI/CD. Configure your workflow to run officecli validate --json and parse the results, or simply use the exit code to fail the job when schema violations exist.
What is the difference between resident mode and standard validation?
Resident mode, handled by ResidentServer.cs, maintains a long-running server process that keeps documents open in memory. When validating a file already handled by the server, the command forwards the request rather than reopening the document, significantly improving performance during batch operations.
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 →