Batch XML Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · XML.now Editorial · XML Essentials

Design a repeatable XML batch process with canaries, logs, validation and rollback.

Canary-Based Preparation

Before any batch conversion, isolate a representative subset of input files to serve as canaries. These files must exercise the full range of XML constructs your production data contains:

  • A minimal file with a single root element and no children.
  • A file with deeply nested elements and mixed content (text interspersed with child elements).
  • A file using XML namespaces, prefixed attributes, and default namespace declarations.
  • A file at or near your anticipated maximum size, including the 80th percentile of expected node counts.

Run the full conversion pipeline against canaries first. If any canary fails well-formedness parsing, schema validation, or produces output that fails re-parsing, stop the entire batch immediately. Do not proceed to production files. A canary failure signals a toolchain defect, encoding mismatch, or incorrect structural assumption that would corrupt every file downstream.

Generate an input inventory before touching any data. Use a CSV with columns: filename, size_bytes, last_modified, md5_hash. This inventory is the authoritative record of original state and the basis for all rollback decisions.

# Generate input inventory with MD5 hashes
find ./input -name '*.xml' -exec sh -c '
  f="$1"
  echo "$(basename "$f"),$(stat -c%s "$f"),$(stat -c%Y "$f"),$(md5sum "$f" | cut -d" " -f1)"
' _ {} \; > pre_inventory.csv

Non-Destructive Transformation

Never modify input files in place. Write all output to a separate directory tree, preserving relative paths from the input root. This guarantees that originals remain available for rollback regardless of conversion outcome.

Select a processor that enforces XML well-formedness natively. The W3C XML specification requires that conforming processors report fatal errors and cease normal processing when encountering malformed input. Do not suppress these errors with flags like --recover or equivalent. Tools that meet this requirement include xmllint (libxml2), xmlstarlet, and Saxon.

For each input file, apply the transformation—XSLT stylesheet, schema migration, or encoding conversion—and write the result to the output directory. Immediately after writing, parse the output file back with a strict XML parser. If re-parsing fails, the output is not XML and must be discarded.

# XSLT conversion with mandatory re-parse
for f in ./input/*.xml; do
  out="./output/$(basename "$f")"
  xsltproc transform.xsl "$f" > "$out" 2>> ./logs/transform_errors.log
  xmllint --noout "$out" 2>> ./logs/wellformedness_errors.log
  if [ $? -ne 0 ]; then
    echo "FAILED: $f" >> ./logs/failed_files.log
    rm -f "$out"
  else
    echo "OK: $f" >> ./logs/success_files.log
  fi
done

Structural and Semantic Validation

Well-formedness alone is insufficient. After every output file passes re-parsing, validate the entire output set against the target schema. Use XSD, RelaxNG, or DTD validation depending on your constraints. The XML specification defines well-formedness; schema languages add structural and content-model constraints. Both checks are mandatory in a safe pipeline.

Generate a post-conversion inventory with identical columns to the pre-conversion inventory. Compare MD5 hashes for files that were not expected to change structurally. Any hash mismatch in these files indicates unintended content drift—a silent corruption that well-formedness and schema checks may not catch.

# Generate post-conversion inventory
find ./output -name '*.xml' -exec sh -c '
  f="$1"
  echo "$(basename "$f"),$(stat -c%s "$f"),$(stat -c%Y "$f"),$(md5sum "$f" | cut -d" " -f1)"
' _ {} \; > post_inventory.csv

# Detect unexpected hash changes in files not targeted for modification
diff <(awk -F, '$1 ~ /^unchanged_/' pre_inventory.csv) \
     <(awk -F, '$1 ~ /^unchanged_/' post_inventory.csv)

Structured Logging for Rollback Decisions

Log every conversion attempt with machine-parseable records. A structured format enables automated rollback without manual log inspection:

{
  "input": "./input/orders_2024.xml",
  "output": "./output/orders_2024.xml",
  "timestamp": "2025-03-27T14:23:11Z",
  "conversion_tool": "xsltproc",
  "exit_code": 0,
  "validation_result": "pass",
  "schema_version": "v2.1"
}

Rollback follows three paths based on failure scope:

  1. Canary failure: Delete the entire output directory. The toolchain or transformation logic is defective. No production files have been touched.
  2. Subset validation failure: Delete only the output files that failed schema validation or re-parsing. Re-run conversion on the corresponding input files with corrected parameters.
  3. Downstream failure after full success: If an application consuming the output later detects corruption, restore all files from the unmodified input directory. The input inventory provides the authoritative hash baseline to confirm integrity.

Schema Compliance Canary

After batch conversion completes and all files pass individual validation, run a final aggregate schema check across the entire output set. Use a schema that enforces the exact expected output format, not a relaxed version.

xmllint --schema output_schema.xsd ./output/*.xml --noout 2> ./logs/schema_errors.log
if [ -s ./logs/schema_errors.log ]; then
  echo "Schema violations detected. See logs/schema_errors.log"
  exit 1
fi

The W3C XML Schema Recommendation requires validators to report all schema violations encountered, not halt at the first error. This catches missing required attributes, incorrect element nesting, and content model violations that well-formedness checks cannot detect.

Hard Limits and Unrecoverable Conditions

Some XML inputs cannot be safely converted in a batch pipeline. Recognize these boundaries during the canary phase and abort rather than produce corrupted output:

  • Files with mismatched encoding declarations: An XML declaration claiming encoding="ISO-8859-1" when the byte stream is actually UTF-8 is unrecoverable without manual inspection. No tool can reliably guess the author's intent.
  • Files with corrupted internal structure: Overlapping tags or unclosed elements that one parser tolerates through error recovery are not XML per the specification. A second parser may reject them, producing inconsistent results across tools.
  • Extremely large files processed with DOM-based tools: DOM parsers load the entire tree into memory. Files exceeding available RAM will cause the process to be killed by the operating system. The only safe approach is switching to a streaming parser (SAX, XMLReader) or splitting the file manually before conversion.
  • Internal DTD subsets with entity expansion: Some parsers expand general entities by default, which can trigger billion-laughs attacks or unintentional content duplication. Pre-process to strip internal DTD subsets if entity expansion is not required, or use a parser with entity expansion explicitly disabled.

When any of these conditions is detected during canary testing, log the specific file and the nature of the unrecoverable problem. Delete the output directory. Do not attempt partial conversion of the remaining files—a batch pipeline must produce consistent, verifiable results across all inputs or produce nothing at all.