XML tools
Python XML Comparison Script with Clear Exit Codes
Create a local XML comparison command with canonicalization, explicit comment handling, preserved text, and separate equal, different, and error results.
Give automation three possible outcomes
A reusable Python script for comparing XML should distinguish equal input, different input and an unreadable or malformed file. If every failure becomes “different,” an automated job may treat a missing export as a normal content change. Use an explicit exit-code contract and preserve the diagnostic message.
The command below compares canonical XML text produced by Python's ElementTree canonicalize function. This handles certain serialization differences such as attribute ordering. It is not a general business-record matcher, and it does not sort repeated records by an application identifier.
Save a small command-line program
Save this code as compare_xml.py. It accepts two paths and an optional comments flag. Exit code zero means equal under this canonicalization policy, one means different, and two means that an input could not be processed. These are choices made by this script, so callers should use the same documented contract.
import argparse
import sys
import xml.etree.ElementTree as ET
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("left")
parser.add_argument("right")
parser.add_argument("--comments", action="store_true")
args = parser.parse_args(argv)
try:
values = [
ET.canonicalize(from_file=path,
with_comments=args.comments,
strip_text=False)
for path in (args.left, args.right)
]
except (OSError, ET.ParseError, ValueError) as error:
print(f"XML comparison failed: {error}", file=sys.stderr)
return 2
equal = values[0] == values[1]
print("Equal under the selected policy" if equal else "Different")
return 0 if equal else 1
if __name__ == "__main__":
raise SystemExit(main())
Run python compare_xml.py before.xml after.xml. Quote a path containing spaces using the quoting rules of your shell. Add --comments when comments are part of the review contract. The script reads both inputs without modifying them and prints one short result for the operator.
Check serialization differences with a known fixture
Put <item b="2" a="1"/> in the first file and <item a="1" b="2"></item> in the second. They should compare equal with this script. Change the second file's a attribute to 3 and expect the “Different” message and exit code one.
Next put a comment inside only one document. The default invocation ignores the comment, while --comments includes it in the comparison. Keep this test in the same job that depends on the result; a later change to the options should be reviewed as a change to comparison semantics.
Avoid an accidental whitespace shortcut
The script explicitly leaves strip_text false. A canonical representation does not mean every indentation or text difference disappears. Whitespace inside the document can remain significant, including spaces in mixed content. Two files with different indentation can therefore still compare different.
Do not enable text stripping merely to make a failing case pass. First decide whether the XML vocabulary allows that whitespace to be discarded. If a producer emits element-only records and your importer has a defined whitespace policy, implement and test that rule separately with representative files.
Keep errors separate from changes
A missing path, invalid closing tag or unsupported input should reach the error branch. In a pipeline, handle exit code two as a failed comparison that needs attention. Capture standard error so that the person investigating can identify the failing file or parser message.
For large documents, this example keeps both canonical strings in memory. Consider a bounded process or temporary canonical files with a streaming comparison when your file sizes require it. Do not expose this local demonstration directly as a public parser for arbitrary hostile uploads.
Python documents the exact function and options in the canonicalize reference. The W3C canonical XML specification explains why canonicalization is a defined transformation rather than general application equivalence. Use the algorithm required by a signature protocol instead of assuming this script verifies signatures.
For a manual review after a “Different” result, inspect the two sources or open a small sample in the XML comparison tool. Retain both original exports and the selected options with the report.


