How to Validate DOCX Files After Creation to Ensure Schema Compliance

Use the DOCXSchemaValidator class from the anthropics/skills repository to unpack DOCX archives and execute 14+ compliance checks against OOXML schemas, XML well-formedness rules, and Office-specific constraints like whitespace preservation and ID uniqueness.

After generating DOCX files programmatically, ensuring they conform to the Office Open XML (OOXML) specification prevents corruption errors when users open them in Microsoft Word or LibreOffice. The anthropics/skills repository provides a robust validation toolkit in skills/docx/scripts/office/validators/docx.py that checks internal XML structure against official schemas while enforcing additional constraints.

Core Validation Architecture

The validation system centers on the DOCXSchemaValidator class, which orchestrates a comprehensive cascade of checks against the unpacked XML components of a DOCX archive.

The DOCXSchemaValidator Class

Located in skills/docx/scripts/office/validators/docx.py, this validator inherits from a base class defined in skills/docx/scripts/office/validators/base.py. It accepts two primary inputs:

  • Unpacked directory: A path to the extracted DOCX contents (the ZIP archive unpacked)
  • Original file (optional): The source DOCX file for redlining comparisons and paragraph count verification

When instantiated, the validator prepares XSD schema references and initializes tracking for ID uniqueness and relationship consistency.

Validation Check Cascade

The validate() method executes the following sub-checks in sequence, returning True only if all pass:

  • validate_xml: Verifies XML well-formedness across all document parts
  • validate_namespaces: Ensures proper namespace declarations per OOXML spec
  • validate_unique_ids: Confirms no duplicate IDs exist across document elements
  • validate_file_references: Validates that all internal file references resolve correctly
  • validate_content_types: Checks [Content_Types].xml declarations against actual file types
  • validate_against_xsd: Performs strict XSD schema validation against official OOXML schemas
  • validate_whitespace_preservation: Ensures w:t text nodes have proper xml:space="preserve" attributes
  • validate_deletions and validate_insertions: Verifies proper handling of tracked changes markup
  • validate_all_relationship_ids: Confirms relationship ID consistency across document parts
  • validate_id_constraints: Validates that ID values fall within acceptable ranges (e.g., paraId, durableId)
  • validate_comment_markers: Ensures comment start/end markers are properly paired
  • compare_paragraph_counts: When an original file is provided, verifies paragraph counts match expectations

Auto-Repair Capabilities

The validator includes a repair() method that automatically fixes common issues:

  • Out-of-range paraId and durableId values are reassigned to valid ranges
  • Missing xml:space="preserve" attributes are added to w:t nodes where required

Call repair() before validate() to maximize compliance without manual intervention.

Command-Line Validation

For immediate validation without writing Python code, use the CLI wrapper located at skills/docx/scripts/office/validate.py.

Basic Validation

Validate a newly created DOCX against its source template:

python -m skills.docx.scripts.office.validate /path/to/generated.docx --original /path/to/original.docx

The script automatically unpacks the DOCX to a temporary directory, instantiates DOCXSchemaValidator, and executes the full validation cascade.

Validation with Auto-Repair

To fix fixable issues before reporting results:

python -m skills.docx.scripts.office.validate /path/to/generated.docx --original /path/to/original.docx --auto-repair

Verbose Output

For detailed reporting of each validation step:

python -m skills.docx.scripts.office.validate /path/to/generated.docx --original /path/to/original.docx --verbose

When an original file is provided, the CLI also invokes the RedliningValidator from skills/pptx/scripts/office/validators/redlining.py to check tracked changes consistency.

Programmatic Integration

Integrate validation into Python workflows using the DOCXSchemaValidator class directly.

Basic Programmatic Validation

from pathlib import Path
from skills.docx.scripts.office.validators import DOCXSchemaValidator

unpacked_dir = Path("/tmp/unpacked_docx")   # Directory containing extracted XML

original_file = Path("/data/template.docx")  # Optional, for redlining checks

validator = DOCXSchemaValidator(
    unpacked_dir,
    original_file,
    verbose=True,
)

# Run all checks

is_valid = validator.validate()
print(f"Schema compliant: {is_valid}")

Validation with Repair


# Instantiate validator

validator = DOCXSchemaValidator(unpacked_dir, original_file)

# Auto-fix common issues

repairs = validator.repair()
print(f"Repaired {repairs} issue(s)")

# Validate after repair

if validator.validate():
    print("DOCX is now schema-compliant")
else:
    print("DOCX failed validation")

Summary

  • Use DOCXSchemaValidator from skills/docx/scripts/office/validators/docx.py to validate DOCX files against OOXML schemas and Office-specific rules.
  • Execute 14+ validation checks covering XML well-formedness, namespace declarations, unique IDs, content types, XSD compliance, whitespace preservation, and comment marker pairing.
  • Leverage auto-repair via the repair() method to fix out-of-range IDs and missing whitespace attributes before validation.
  • Use the CLI at skills/docx/scripts/office/validate.py for command-line validation with --original, --verbose, and --auto-repair options.
  • Integrate programmatically by instantiating DOCXSchemaValidator with unpacked directory paths and optional original files for redlining verification.

Frequently Asked Questions

What specific schema violations does the validator detect?

The validator detects XML well-formedness errors, incorrect namespace declarations, duplicate IDs, broken file references, mismatched content-type declarations, and XSD schema violations against official OOXML standards. It also enforces Office-specific rules such as proper xml:space="preserve" attributes on text nodes, valid ID ranges for paraId and durableId, and paired comment markers.

Can the validator automatically fix corrupted DOCX files?

Yes, the repair() method automatically fixes common issues including out-of-range ID values and missing whitespace preservation attributes. However, it cannot repair structural XML corruption or schema violations that require semantic changes; these require manual intervention after the validator identifies them.

How do I validate a DOCX against its original template?

Pass the original file path to the validator constructor or use the --original CLI flag. When provided, the validator runs compare_paragraph_counts to ensure the generated document maintains structural parity with the template, and invokes the RedliningValidator to verify tracked changes consistency.

What is the difference between XSD validation and the additional Office-specific checks?

XSD validation (validate_against_xsd) verifies that XML documents conform to the official OOXML schema definitions. The additional Office-specific checks enforce runtime constraints that schemas cannot express, such as cross-document ID uniqueness, relationship consistency between parts, proper handling of revision markup, and whitespace preservation requirements on text elements.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →