OfficeCLI Validate Command: OpenXML Schema Checking for Office Documents
The officecli validate command uses the official Open XML SDK to check Word, Excel, and PowerPoint files against ECMA-376/ISO-29500 schema definitions, reporting structural violations through CLI output or JSON.
OfficeCLI is a cross-platform command-line tool for Microsoft Office document automation. Its validate command provides OpenXML schema checking to ensure DOCX, XLSX, and PPTX files conform to official specifications. This article explains how the validation pipeline works, where to find the implementation in the iOfficeAI/OfficeCLI repository, and how to use it across all supported languages.
How OfficeCLI Validation Works
The validation system follows a four-stage pipeline implemented in .NET 6 and exposed through multiple language SDKs.
Stage 1: Command Parsing
In src/officecli/CommandBuilder.Mark.cs, the CLI constructs the command hierarchy and routes the validate verb to its handler. The CommandBuilder pattern separates argument parsing from execution logic.
// Simplified representation of the routing mechanism
// Located in: src/officecli/CommandBuilder.Mark.cs
var validateCommand = new Command("validate", "Validate file against OpenXML schema");
validateCommand.AddArgument(new Argument<FileInfo>("file"));
validateCommand.SetHandler((file) => ValidateHandler.Execute(file));
Stage 2: File Loading
The handler opens the target file using the Open XML SDK (DocumentFormat.OpenXml package). It automatically detects document type and instantiates the appropriate package class:
WordprocessingDocumentfor.docxSpreadsheetDocumentfor.xlsxPresentationDocumentfor.pptx
Stage 3: Schema Validation
The core validation occurs through OpenXmlValidator.Validate() as implemented in the Open XML SDK. According to the iOfficeAI/OfficeCLI source code, this method:
- Parses each package part
- Compares against ECMA-376 and ISO-29500 schema definitions
- Collects
ValidationErrorInfoobjects for violations
// Core validation pattern from the CLI implementation
// In: src/officecli/Handlers/ValidateHandler.cs (implied structure)
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
public ValidationReport RunValidation(string path)
{
using var doc = WordprocessingDocument.Open(path, false);
var validator = new OpenXmlValidator();
var errors = validator.Validate(doc);
return new ValidationReport(errors);
}
Stage 4: Result Formatting
Errors are aggregated and output to standard output. The CLI supports optional JSON export for programmatic consumption.
Using the OfficeCLI Validate Command
Command-Line Interface
The primary interface accepts a file path and returns validation results immediately:
officecli validate ./documents/Report.docx
Common options:
--format json— Output machine-readable JSON--strict— Enforce strict ISO-29500 compliance (rejects transitional extensions)
Node.js SDK
The Node SDK in sdk/node/index.js forks the native binary and returns a Promise with structured results:
const { validate } = require('officecli');
async function checkDocument(path) {
const report = await validate(path);
if (report.errors.length === 0) {
console.log('✓ Document passes OpenXML schema validation');
return true;
}
console.error(`✗ ${report.errors.length} validation errors found:`);
report.errors.forEach(err => {
console.error(` - ${err.description} (${err.path})`);
});
return false;
}
checkDocument('./documents/Report.docx')
.catch(err => console.error('Validation failed to run:', err));
Python SDK
The Python wrapper in sdk/python/officecli.py provides a synchronous function that wraps subprocess execution:
from officecli import validate
def validate_office_file(path: str) -> dict:
"""
Validate a DOCX, XLSX, or PPTX file against OpenXML schema.
Returns dict with 'valid' bool and 'errors' list.
"""
report = validate(path)
if report["errors"]:
print(f"Found {len(report['errors'])} schema violations:")
for error in report["errors"]:
print(f" • {error['description']} in {error['part']}")
return {"valid": False, "details": report}
print("Document conforms to OpenXML specification")
return {"valid": True, "details": report}
# Usage
result = validate_office_file("./documents/Budget.xlsx")
Key Implementation Files
Understanding these source files helps extend or debug the validation system:
| File | Purpose |
|---|---|
src/officecli/officecli.csproj |
.NET 6 project definition; references DocumentFormat.OpenXml |
src/officecli/CommandBuilder.Mark.cs |
CLI command tree construction; registers validate verb |
src/officecli/CommandBuilder.IntegrationStubs.cs |
Thin wrappers bridging CLI core to language SDKs |
sdk/node/index.js |
Node.js entry point; handles binary forking and JSON parsing |
sdk/python/officecli.py |
Python module; subprocess wrapper with error handling |
Validation Error Types
The Open XML SDK validator reports several categories of issues detectable through OfficeCLI:
- Structural errors — Missing required parts or invalid relationships
- Content type mismatches — Parts with incorrect MIME types
- Schema constraint violations — Elements/attributes that violate XSD rules
- Compatibility warnings — Features not supported in target format version
Example error output:
{
"valid": false,
"errors": [
{
"id": "Sch_InvalidElementContentExpectingComplex",
"description": "The element has invalid child element",
"path": "/word/document.xml",
"element": "w:t",
"expected": "w:rPr"
}
]
}
Summary
- OfficeCLI validate provides built-in OpenXML schema checking using the official Microsoft Open XML SDK
- The validation pipeline runs through
CommandBuilder.Mark.cs→ package loading →OpenXmlValidator.Validate()→ formatted output - Three interfaces are available: direct CLI, Node.js SDK (
sdk/node/index.js), and Python SDK (sdk/python/officecli.py) - Validation covers DOCX, XLSX, and PPTX against ECMA-376 and ISO-29500 specifications
- Errors include structural, content-type, and schema constraint violations with precise location data
Frequently Asked Questions
What document formats does OfficeCLI validate support?
OfficeCLI validates DOCX (Word), XLSX (Excel), and PPTX (PowerPoint) files through the Open XML SDK's automatic format detection. The validator opens files in read-only mode and selects the appropriate OpenXmlPackage subclass based on content type.
How does OfficeCLI validation differ from Office's built-in checker?
OfficeCLI performs strict schema validation against published ECMA-376/ISO-29500 specifications, while Microsoft Office applications often apply lenient parsing and automatic repair. A document that opens in Word may still fail OfficeCLI validation if it contains technically invalid markup that Office silently corrects.
Can I integrate OfficeCLI validation into CI/CD pipelines?
Yes. The CLI's --format json option produces machine-readable output suitable for automated testing. Exit codes indicate validation status (0 for valid, non-zero for errors), and the Node/Python SDKs provide native integration with test frameworks. Example GitHub Actions step:
- name: Validate Office documents
run: |
for file in docs/*.docx; do
officecli validate "$file" --format json || exit 1
done
Where does OfficeCLI get its schema definitions?
Schema definitions are embedded in the Open XML SDK (DocumentFormat.OpenXml package) referenced in src/officecli/officecli.csproj. This ensures validation always uses current standards without requiring separate Schema downloads or updates.
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 →