Well-Formed vs Valid XML: The Difference and How to Test Both
Build beyond the existing well-formedness page with schema validation, diagnostics and workflow.
Structure vs. Contract: Testing XML Well-Formedness and Schema Validity
A document that parses without error can still fail when it reaches a schema-aware processor or a downstream system with fixed expectations. The file is well-formed—every tag closes, no illegal characters appear—but it is not valid. Distinguishing these two states, and testing for each explicitly, determines whether data survives integration, validation, or conversion.
The Symptom: Parsing Succeeds, Logic Fails
Well-formedness is a syntactic property. The W3C XML 1.0 Recommendation, section 2.1, defines it: a single root element, correctly nested tags, quoted attribute values, and proper escaping of markup characters (<, &, etc.). A conforming parser must halt at the first well-formedness error—a missing closing tag or an unescaped ampersand stops processing entirely.
Validity, defined in section 2.8, requires conformance to a formal schema: a DTD, W3C XML Schema (XSD), or Relax NG grammar. A valid document must be well-formed first, then satisfy structural constraints—element order, required attributes, cardinality, and data types. A file that passes a basic syntax check but breaks an integration pipeline is typically well-formed but invalid.
Testing Well-Formedness: Observable Checks
Use xmllint (part of libxml2, available on Linux and macOS; on Windows via WSL or Cygwin):
xmllint --noout yourfile.xml
- Exit code 0: The document is well-formed. No syntax errors.
- Exit code 1: The parser encountered an error. The error message includes a line number and description (e.g.,
parser error : Opening and ending tag mismatch).
Do not add --valid or --schema for this check. Those flags trigger validation, which is a separate step.
What well-formedness does not guarantee:
- Correct element ordering per a business contract
- Presence of required attributes
- Data type conformance (a
<date>element containing"hello") - Namespace correctness (a wrong URI does not break well-formedness)
- Structural depth within parser limits (some parsers reject documents nested beyond a configured maximum, but this is an implementation limit, not a W3C rule)
A well-formed document can contain a <price> element with a negative value when the schema requires non-negative decimals. The parser will not flag it.
Testing Validity: Schema-Driven Diagnostics
Validity requires a schema. To validate against an XSD file:
xmllint --schema my_schema.xsd --noout yourfile.xml
- Success:
yourfile.xml validates - Failure: A line number and a specific constraint violation, for example:
Element 'price': 'abc' is not a valid value of the atomic type 'xs:decimal'.
If the XML document references a DTD internally via <!DOCTYPE>, xmllint can validate against it with the --valid flag. However, DTDs cannot express data types or namespace constraints. XSD supports types, patterns, enumerations, and min/max occurrences. The schema is typically a separate file, referenced in the XML via xsi:schemaLocation or passed directly to the validator.
What validity does not guarantee:
- Encoding correctness (well-formedness covers the encoding declaration; a mismatch between declared and actual encoding is a well-formedness error, not a validity error)
- Cross-element logical consistency (e.g., start date before end date)
- Application-level rules not expressed in the schema
Failure Modes During Conversion
Conversion tools (XML-to-CSV, XML-to-JSON, XML-to-XLSX) operate on the parsed tree. When a document is well-formed but invalid, the converter may:
- Omit fields for missing required elements
- Coerce types incorrectly (treating
12.5as an integer when the schema expectsxs:integer) - Drop entire records when a parent element fails a schema constraint
Hard limits in validation and conversion:
- Depth recursion: Some validators limit element nesting to a few hundred levels. A deeply nested but well-formed document may exhaust the call stack during schema traversal.
- Schema recursion: Circular type definitions in XSD (an element containing itself) are legal but can cause stack overflow in validators that do not guard against unbounded recursion.
- Encoding mismatches: A document declared as UTF-8 that contains bytes invalid for UTF-8 fails well-formedness, not validity. Converters typically refuse such files outright.
- Memory limits: Many validators load the entire document into memory. A well-formed multi-gigabyte file may trigger an out-of-memory error during validation, even if a streaming parser handles it.
A Two-Stage Workflow for Incoming Data
Isolate issues before they reach downstream systems.
Stage 1: Fast syntax check
xmllint --noout incoming_data.xml || echo "Not well-formed. Reject."
If this fails, stop. Do not attempt validation or conversion. The file is structurally broken.
Stage 2: Schema validation with diagnostics
xmllint --schema my_schema.xsd --noout incoming_data.xml 2> validation_errors.log
if [ $? -ne 0 ]; then
echo "Validation failed. See validation_errors.log"
fi
For batch workflows, log errors per file. Tools like xmlstarlet or Saxon can report line numbers and element paths, making it possible to locate the exact failure point in large documents.
When to accept invalid input:
- You control the schema and can relax constraints (e.g., making an attribute optional)
- The data comes from a trusted source and the schema is known to be overly strict
- You are performing exploratory analysis and need the tree structure, not type safety
In all other cases, treat validation failures as data defects.
Distinguishing Structure, Metadata, Application Behavior, and Appearance
Conflating these layers causes misdiagnosis.
| Layer | What It Governs | Example Failure |
|---|---|---|
| Structure | Parsing, tree construction | Unclosed tag → no parse |
| Metadata | Schema association, namespace declarations, encoding label | Wrong namespace URI → elements not recognized by schema validator |
| Application behavior | Business logic, data processing | Missing required element → downstream system skips record |
| Visual appearance | How an editor or formatter displays the file | Indentation, line breaks (no effect on parsing or validation) |
A document can be well-formed, valid, and neatly indented yet still cause an application to fail if the application expects <price> but the schema defines <cost>. The schema and the application contract must match. The XML specification defines grammar and schema languages; it does not define application semantics.
Testing Without a Schema: Heuristic Structural Checks
When no formal schema exists, you can compare against a known-good document.
Extract element paths and diff them:
xmlstarlet el -u known_good.xml | sort > good_paths.txt
xmlstarlet el -u suspect.xml | sort > suspect_paths.txt
diff good_paths.txt suspect_paths.txt
Check for missing attributes with XPath:
xmllint --xpath '//*[not(@id)]' suspect.xml 2>/dev/null
This lists elements without an id attribute, if id is expected.
These techniques are heuristic. They detect structural drift but cannot enforce cardinality, types, or ordering constraints. They do not replace a formal schema for production validation.