# OfficeCLI Validate Command: How It Verifies OpenXML Schema Compliance

> Learn how the OfficeCLI validate command ensures OpenXML schema compliance through multi-layered checks including pre-flight XML, relationship detection, and the official OpenXmlValidator.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-08-10

---

**The OfficeCLI `validate` command performs multi-layered OpenXML schema validation by flushing pending changes, cloning the document to a memory stream, running pre-flight XML checks, detecting orphaned relationships, and executing the official `OpenXmlValidator` while filtering known false-positives.**

The `validate` command in [iOfficeAI/OfficeCLI](https://github.com/iOfficeAI/OfficeCLI) provides comprehensive **OpenXML schema compliance verification** for Word, Excel, and PowerPoint documents. This article breaks down the complete validation pipeline implemented in the source code, from CLI entry point to error reporting.

## CLI Entry Point: CommandBuilder.Check.cs

The validation journey begins in [`CommandBuilder.Check.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Check.cs), which constructs the `validate` command and wires it to the document handler system.

```csharp
// CommandBuilder.Check.cs – lines 12-20
var validateCommand = new Command("validate", "Validate document against OpenXML schema");
validateCommand.Add(validateFileArg);
validateCommand.Add(jsonOption);
validateCommand.SetAction(result => { … });

```

When executed, the command:

1. Opens the target file via `DocumentHandlerFactory.Open`
2. Invokes the handler's `Validate()` method
3. Formats results as either human-readable text or JSON

## Handler Delegation: WordHandler, ExcelHandler, PowerPointHandler

Each document type handler implements `Validate()` as a thin wrapper around `RawXmlHelper.ValidateDocument`. In [`WordHandler.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.cs) (lines 2211-2214):

```csharp
public List<ValidationError> Validate() => RawXmlHelper.ValidateDocument(_doc, _filePath);

```

The `ExcelHandler` and `PowerPointHandler` follow identical patterns, ensuring consistent validation across all Office OpenXML formats.

## Core Validation Logic: RawXmlHelper.ValidateDocument

The `RawXmlHelper.ValidateDocument` method (lines 55-94 in [`RawXmlHelper.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/RawXmlHelper.cs)) implements a **seven-stage validation pipeline**:

### 1. Flush Dirty Parts

`FlushLoadedPartRoots` persists any in-memory DOM modifications to the package streams, ensuring the validation clone reflects all pending changes.

```csharp
// FlushLoadedPartRoots – lines 70-88
// Writes in-memory changes to package streams before cloning

```

### 2. Clone the Package

A memory-stream clone guarantees **read-only validation**:

```csharp
package.Clone(cloneStream, false)  // false = non-destructive clone

```

This prevents the validator from mutating the live document.

### 3. Pre-flight XML Parsing

`PreflightXmlParts` (lines 13-25) walks each XML part, parses it, and surfaces malformed XML as synthetic `ValidationError` objects before the SDK validator runs.

### 4. Detect Orphaned Header/Footer References

`DetectOrphanedHeaderFooterReferences` (lines 33-44) explicitly validates that `<w:headerReference>` and `<w:footerReference>` elements point to existing parts, preventing silent `NullReferenceException` failures.

### 5. Verify Default `.rels` Content-Type

`DetectMissingDefaultRelsContentType` (lines 48-56) adds a critical check for the required `[Content_Types].xml` entry:

```xml
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>

```

Missing this entry commonly triggers "file may be corrupt" errors in Microsoft Office applications.

### 6. Execute Official OpenXmlValidator

The `OpenXmlValidator` from the Open XML SDK performs strict schema validation against the ECMA-376 and ISO/IEC 29500 specifications. Errors are wrapped in `ValidationError` objects with part locations and descriptions.

### 7. Filter Known False-Positives

Benign errors—such as `chartEx` attribute validation issues—are removed via `IsBenignChartExValAttributeError`, reducing noise in validation reports.

## Output Formatting

Validation results flow through two paths based on the `--json` flag:

| Mode | Implementation | Use Case |
|------|---------------|----------|
| Human-readable | Direct stdout/stderr writing | Interactive debugging |
| JSON | `OutputFormatter.WrapEnvelope` | CI/CD pipeline integration |

Exit code **1** signals validation failures, enabling shell script automation.

## Practical Usage Examples

### Command Line Validation

```bash

# Standard human-readable report

officecli validate path/to/document.docx

# JSON output for automation

officecli validate path/to/document.docx --json

```

### Programmatic Validation

```csharp
using OfficeCli.Core;
using OfficeCli.Handlers;

// Open document (read-only)
var handler = DocumentHandlerFactory.Open(@"C:\Docs\report.docx");

// Execute validation
List<ValidationError> errors = handler.Validate();

// Process results
if (errors.Count == 0)
{
    Console.WriteLine("OpenXML schema validation passed.");
}
else
{
    foreach (var err in errors)
    {
        Console.WriteLine($"{err.ErrorType}: {err.Description}");
        Console.WriteLine($"  Part: {err.Part}");
        Console.WriteLine($"  Line: {err.LineNumber}");
    }
}

```

## Architecture Benefits

The OfficeCLI validation pipeline provides **four key protections** unavailable in raw SDK validation:

- **Immutability guarantee**: Memory-stream cloning prevents accidental document modification
- **Early error detection**: Pre-flight checks catch malformed XML and orphaned relationships before expensive schema validation
- **Package integrity**: Explicit content-type verification prevents subtle corruption issues
- **Clean output**: False-positive filtering delivers actionable error reports

## Summary

- **[`CommandBuilder.Check.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Check.cs)** constructs the `validate` CLI command with `--json` output option
- **`DocumentHandlerFactory.Open`** resolves file extensions to typed handlers (`WordHandler`, `ExcelHandler`, `PowerPointHandler`)
- **`RawXmlHelper.ValidateDocument`** executes the seven-stage validation: flush, clone, pre-flight XML, orphaned reference detection, content-type verification, SDK validation, and false-positive filtering
- **Exit code 1** indicates failures; JSON output enables CI pipeline integration
- The **memory-stream clone** ensures read-only operation while the **pre-flight checks** catch errors the SDK validator misses

## Frequently Asked Questions

### What file formats does the OfficeCLI validate command support?

The `validate` command supports all Office OpenXML formats: `.docx` (Word), `.xlsx` (Excel), and `.pptx` (PowerPoint). `DocumentHandlerFactory.Open` automatically detects the file extension and instantiates the appropriate handler (`WordHandler`, `ExcelHandler`, or `PowerPointHandler`), each delegating to the same `RawXmlHelper.ValidateDocument` core logic.

### Why does validation use a memory-stream clone instead of the original file?

The `package.Clone(cloneStream, false)` operation guarantees that **validation never mutates the live document**. Some validation operations in the Open XML SDK can trigger side effects; cloning to a memory stream isolates these while preserving the ability to detect all schema violations. This approach also works with documents opened from read-only sources.

### What orphaned relationships does OfficeCLI detect that the SDK validator misses?

`DetectOrphanedHeaderFooterReferences` specifically validates that `w:headerReference` and `w:footerReference` elements in Word documents point to existing parts in the package. The SDK validator may encounter null references during validation and fail silently or throw unhelpful exceptions; OfficeCLI surfaces these as explicit `ValidationError` objects with clear descriptions and part locations.

### How can I integrate OfficeCLI validation into a CI/CD pipeline?

Use the `--json` flag to emit machine-parseable output: `officecli validate document.docx --json`. The command returns exit code **1** when validation fails, enabling standard shell conditional logic. JSON output includes structured `ValidationError` objects with `ErrorType`, `Description`, `Part`, and `LineNumber` properties suitable for automated reporting and quality gates.