xml-checker 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wing Kui Tsoi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: xml-checker
3
+ Version: 1.0.0
4
+ Summary: A Python toolkit for parsing and comparing XML files.
5
+ Author: Wing Kui Tsoi
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wingkuitsoi/xml-checker
8
+ Project-URL: Repository, https://github.com/wingkuitsoi/xml-checker
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Text Processing :: Markup :: XML
13
+ Requires-Python: >=3.12
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # xml-checker
19
+
20
+ A Python toolkit for parsing and comparing XML files.
21
+
22
+ ## Overview
23
+
24
+ | Script | Purpose |
25
+ |--------|---------|
26
+ | `xml_parser.py` | Parse XML/text files into `ET.Element` objects with robust pre-processing |
27
+ | `xml_diff.py` | Compare two parsed XML objects and produce a structured diff report |
28
+
29
+ ## Requirements
30
+
31
+ - Python 3.12+
32
+ - Standard library only (no third-party dependencies)
33
+
34
+ ---
35
+
36
+ ## xml_parser.py
37
+
38
+ Reads an XML or text file and returns a list of top-level `ET.Element` objects.
39
+ Files with multiple root-level elements are supported by wrapping content in a temporary `<_root_>` element before parsing.
40
+
41
+ **Pre-processing pipeline** (applied in order before parsing):
42
+
43
+ | Step | What is removed |
44
+ |------|----------------|
45
+ | 1 | `<!-- comments -->` |
46
+ | 2 | `<!DOCTYPE ...>` declarations (including internal DTD subsets) |
47
+ | 3 | Processing instructions `<?...?>` (the XML declaration `<?xml ...?>` is kept until step 4) |
48
+ | 4 | XML declaration `<?xml ...?>` |
49
+ | 5 | Custom `&entity;` references (built-ins `&amp;`, `&lt;`, `&gt;`, `&apos;`, `&quot;` are preserved) |
50
+
51
+ Namespace URIs are stripped from all tag names and attribute keys after parsing.
52
+
53
+ ### CLI
54
+
55
+ ```
56
+ python xml_parser.py <file.xml|file.txt> [output.txt]
57
+ ```
58
+
59
+ Output file defaults to `output.txt`.
60
+
61
+ ### Python API
62
+
63
+ ```python
64
+ from xml_parser import parse_file, display_elements, save_elements_to_file
65
+
66
+ elements = parse_file("input.xml") # list[ET.Element]
67
+ display_elements(elements) # print to stdout
68
+ save_elements_to_file(elements, "out.txt") # write to file
69
+ ```
70
+
71
+ ---
72
+
73
+ ## xml_diff.py
74
+
75
+ Compares two XML objects and generates a detailed diff report covering:
76
+
77
+ - **Summary** – total tags, tags exclusive to each object, common tags, and total attribute differences.
78
+ - **Tag differences** – element paths present in one object but not the other.
79
+ - **Attribute differences** – per-element, per-attribute value comparison (grouped by depth level).
80
+
81
+ ### CLI
82
+
83
+ ```
84
+ python xml_diff.py <file1.xml|file1.txt> <file2.xml|file2.txt> [output.txt] [--tag-key=<attr>]
85
+ ```
86
+
87
+ | Argument | Required | Description |
88
+ |----------|----------|-------------|
89
+ | `file1` | Yes | First XML file |
90
+ | `file2` | Yes | Second XML file |
91
+ | `output.txt` | No | Report output path (default: `output.txt`) |
92
+ | `--tag-key=<attr>` | No | Attribute used to disambiguate sibling elements in paths (default: `id`) |
93
+
94
+ ### Python API
95
+
96
+ ```python
97
+ from xml_parser import parse_file
98
+ from xml_diff import build_report, save_report
99
+
100
+ obj1 = parse_file("a.xml")
101
+ obj2 = parse_file("b.xml")
102
+
103
+ report = build_report(obj1, obj2, tag_key="id")
104
+ print(report)
105
+ save_report(report, "output.txt")
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Sample Files
111
+
112
+ The `samples/` folder contains example files organised by use case.
113
+
114
+ ### Parser samples — `samples/parser/`
115
+
116
+ | Input | Expected output | Description |
117
+ |-------|----------------|-------------|
118
+ | `simple.xml` | `simple_output.txt` | Basic XML with nested elements and attributes |
119
+ | `complex.xml` | `complex_output.txt` | Demonstrates all pre-processing: comments, DOCTYPE, processing instructions, namespaces, and entity references |
120
+
121
+ ```
122
+ python xml_parser.py samples/parser/simple.xml samples/parser/simple_output.txt
123
+ python xml_parser.py samples/parser/complex.xml samples/parser/complex_output.txt
124
+ ```
125
+
126
+ ### Diff samples — `samples/diff/`
127
+
128
+ | File pair | Expected report | Scenario |
129
+ |-----------|----------------|----------|
130
+ | `empty_a.xml` / `empty_b.xml` | `empty_report.txt` | Both files contain no XML elements → `"Both objects are empty, so there is nothing to compare."` |
131
+ | `same_a.xml` / `same_b.xml` | `same_report.txt` | Identical XML structure and attributes → no differences reported |
132
+ | `different_a.xml` / `different_b.xml` | `different_report.txt` | Server configs with differing hosts, ports, drivers, and feature sets → full diff report |
133
+
134
+ ```
135
+ python xml_diff.py samples/diff/empty_a.xml samples/diff/empty_b.xml samples/diff/empty_report.txt
136
+ python xml_diff.py samples/diff/same_a.xml samples/diff/same_b.xml samples/diff/same_report.txt
137
+ python xml_diff.py samples/diff/different_a.xml samples/diff/different_b.xml samples/diff/different_report.txt
138
+ ```
@@ -0,0 +1,121 @@
1
+ # xml-checker
2
+
3
+ A Python toolkit for parsing and comparing XML files.
4
+
5
+ ## Overview
6
+
7
+ | Script | Purpose |
8
+ |--------|---------|
9
+ | `xml_parser.py` | Parse XML/text files into `ET.Element` objects with robust pre-processing |
10
+ | `xml_diff.py` | Compare two parsed XML objects and produce a structured diff report |
11
+
12
+ ## Requirements
13
+
14
+ - Python 3.12+
15
+ - Standard library only (no third-party dependencies)
16
+
17
+ ---
18
+
19
+ ## xml_parser.py
20
+
21
+ Reads an XML or text file and returns a list of top-level `ET.Element` objects.
22
+ Files with multiple root-level elements are supported by wrapping content in a temporary `<_root_>` element before parsing.
23
+
24
+ **Pre-processing pipeline** (applied in order before parsing):
25
+
26
+ | Step | What is removed |
27
+ |------|----------------|
28
+ | 1 | `<!-- comments -->` |
29
+ | 2 | `<!DOCTYPE ...>` declarations (including internal DTD subsets) |
30
+ | 3 | Processing instructions `<?...?>` (the XML declaration `<?xml ...?>` is kept until step 4) |
31
+ | 4 | XML declaration `<?xml ...?>` |
32
+ | 5 | Custom `&entity;` references (built-ins `&amp;`, `&lt;`, `&gt;`, `&apos;`, `&quot;` are preserved) |
33
+
34
+ Namespace URIs are stripped from all tag names and attribute keys after parsing.
35
+
36
+ ### CLI
37
+
38
+ ```
39
+ python xml_parser.py <file.xml|file.txt> [output.txt]
40
+ ```
41
+
42
+ Output file defaults to `output.txt`.
43
+
44
+ ### Python API
45
+
46
+ ```python
47
+ from xml_parser import parse_file, display_elements, save_elements_to_file
48
+
49
+ elements = parse_file("input.xml") # list[ET.Element]
50
+ display_elements(elements) # print to stdout
51
+ save_elements_to_file(elements, "out.txt") # write to file
52
+ ```
53
+
54
+ ---
55
+
56
+ ## xml_diff.py
57
+
58
+ Compares two XML objects and generates a detailed diff report covering:
59
+
60
+ - **Summary** – total tags, tags exclusive to each object, common tags, and total attribute differences.
61
+ - **Tag differences** – element paths present in one object but not the other.
62
+ - **Attribute differences** – per-element, per-attribute value comparison (grouped by depth level).
63
+
64
+ ### CLI
65
+
66
+ ```
67
+ python xml_diff.py <file1.xml|file1.txt> <file2.xml|file2.txt> [output.txt] [--tag-key=<attr>]
68
+ ```
69
+
70
+ | Argument | Required | Description |
71
+ |----------|----------|-------------|
72
+ | `file1` | Yes | First XML file |
73
+ | `file2` | Yes | Second XML file |
74
+ | `output.txt` | No | Report output path (default: `output.txt`) |
75
+ | `--tag-key=<attr>` | No | Attribute used to disambiguate sibling elements in paths (default: `id`) |
76
+
77
+ ### Python API
78
+
79
+ ```python
80
+ from xml_parser import parse_file
81
+ from xml_diff import build_report, save_report
82
+
83
+ obj1 = parse_file("a.xml")
84
+ obj2 = parse_file("b.xml")
85
+
86
+ report = build_report(obj1, obj2, tag_key="id")
87
+ print(report)
88
+ save_report(report, "output.txt")
89
+ ```
90
+
91
+ ---
92
+
93
+ ## Sample Files
94
+
95
+ The `samples/` folder contains example files organised by use case.
96
+
97
+ ### Parser samples — `samples/parser/`
98
+
99
+ | Input | Expected output | Description |
100
+ |-------|----------------|-------------|
101
+ | `simple.xml` | `simple_output.txt` | Basic XML with nested elements and attributes |
102
+ | `complex.xml` | `complex_output.txt` | Demonstrates all pre-processing: comments, DOCTYPE, processing instructions, namespaces, and entity references |
103
+
104
+ ```
105
+ python xml_parser.py samples/parser/simple.xml samples/parser/simple_output.txt
106
+ python xml_parser.py samples/parser/complex.xml samples/parser/complex_output.txt
107
+ ```
108
+
109
+ ### Diff samples — `samples/diff/`
110
+
111
+ | File pair | Expected report | Scenario |
112
+ |-----------|----------------|----------|
113
+ | `empty_a.xml` / `empty_b.xml` | `empty_report.txt` | Both files contain no XML elements → `"Both objects are empty, so there is nothing to compare."` |
114
+ | `same_a.xml` / `same_b.xml` | `same_report.txt` | Identical XML structure and attributes → no differences reported |
115
+ | `different_a.xml` / `different_b.xml` | `different_report.txt` | Server configs with differing hosts, ports, drivers, and feature sets → full diff report |
116
+
117
+ ```
118
+ python xml_diff.py samples/diff/empty_a.xml samples/diff/empty_b.xml samples/diff/empty_report.txt
119
+ python xml_diff.py samples/diff/same_a.xml samples/diff/same_b.xml samples/diff/same_report.txt
120
+ python xml_diff.py samples/diff/different_a.xml samples/diff/different_b.xml samples/diff/different_report.txt
121
+ ```
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xml-checker"
7
+ version = "1.0.0"
8
+ description = "A Python toolkit for parsing and comparing XML files."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Wing Kui Tsoi" }]
13
+ requires-python = ">=3.12"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Text Processing :: Markup :: XML",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/wingkuitsoi/xml-checker"
23
+ Repository = "https://github.com/wingkuitsoi/xml-checker"
24
+
25
+ [project.scripts]
26
+ xml-parser = "xml_checker.xml_parser:main"
27
+ xml-diff = "xml_checker.xml_diff:main"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["."]
31
+ include = ["xml_checker*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,47 @@
1
+ """
2
+ xml-checker — A Python toolkit for parsing and comparing XML files.
3
+
4
+ Modules:
5
+ xml_parser: Parse XML/text files into ET.Element objects with robust pre-processing.
6
+ xml_diff: Compare two parsed XML objects and produce a structured diff report.
7
+ """
8
+
9
+ from .xml_parser import (
10
+ parse_file,
11
+ display_elements,
12
+ save_elements_to_file,
13
+ preprocess,
14
+ strip_comments,
15
+ strip_doctype,
16
+ strip_processing_instructions,
17
+ strip_xml_declaration,
18
+ strip_entity_refs,
19
+ strip_namespaces,
20
+ )
21
+ from .xml_diff import (
22
+ build_report,
23
+ save_report,
24
+ find_diff,
25
+ collect_paths,
26
+ elem_label,
27
+ )
28
+
29
+ __all__ = [
30
+ # xml_parser
31
+ "parse_file",
32
+ "display_elements",
33
+ "save_elements_to_file",
34
+ "preprocess",
35
+ "strip_comments",
36
+ "strip_doctype",
37
+ "strip_processing_instructions",
38
+ "strip_xml_declaration",
39
+ "strip_entity_refs",
40
+ "strip_namespaces",
41
+ # xml_diff
42
+ "build_report",
43
+ "save_report",
44
+ "find_diff",
45
+ "collect_paths",
46
+ "elem_label",
47
+ ]
@@ -0,0 +1,259 @@
1
+ """
2
+ xml_diff.py — Compare two XML objects parsed from files and produce a diff report.
3
+
4
+ Provides build_report() to compare two ET.Element trees and generate a detailed diff report covering:
5
+
6
+ • Tag count summary: total nested tags, tags only in object 1 / only in object 2.
7
+ • Attribute-level diff (level by level): every element present in both trees is compared attribute by attribute;
8
+ differing values are listed.
9
+
10
+ Usage:
11
+ python xml_diff.py <file1.xml|file1.txt> <file2.xml|file2.txt> [output.txt] [--tag-key=<attr>]
12
+
13
+ Python: 3.12
14
+ Author: Wing Kui, Tsoi
15
+ Coauthor: AI
16
+ Last Updated: 2026-11-30
17
+ """
18
+
19
+ import sys
20
+ import xml.etree.ElementTree as ET
21
+ from collections import defaultdict
22
+
23
+ from .xml_parser import *
24
+
25
+
26
+ # ----- Tree diff -----
27
+
28
+
29
+ def elem_label(elem: ET.Element, tag_key: str = "id") -> str:
30
+ """Return a human-readable label for *elem* used to build element paths.
31
+
32
+ Args:
33
+ elem: The XML element to label.
34
+ tag_key: Attribute whose value is appended to the tag name (e.g. "id", "name"). Defaults to "id".
35
+
36
+ Returns:
37
+ "{elem.tag}[{value}]" when the attribute exists, else "{elem.tag}".
38
+ """
39
+ val = elem.get(tag_key)
40
+ return f"{elem.tag}[{val}]" if val else elem.tag
41
+
42
+
43
+ def collect_paths(element: ET.Element, prefix: str = "", tag_key: str = "id") -> dict[str, ET.Element]:
44
+ """Return {path: element} for every descendant of *element*.
45
+
46
+ Sibling elements sharing the same tag are disambiguated using tag_key,
47
+ so that duplicate tag names within a parent each receive a unique path.
48
+
49
+ Args:
50
+ element: The root XML element whose descendants are collected.
51
+ prefix: Path string accumulated from parent calls; leave as default for the initial call.
52
+ tag_key: Attribute used to disambiguate sibling elements (e.g. "id", "name"). Defaults to "id".
53
+
54
+ Returns:
55
+ A dict mapping each path string to its corresponding element.
56
+ """
57
+ result: dict[str, ET.Element] = {}
58
+ #counter: dict[str, int] = defaultdict(int)
59
+
60
+ for child in element:
61
+ label = elem_label(child, tag_key)
62
+ #idx = counter[label]
63
+ #counter[label] += 1
64
+ #path = f"{prefix}/{label}#{idx}" # show position by index
65
+ path = f"{prefix}/{label}"
66
+ result[path] = child
67
+ result.update(collect_paths(child, path, tag_key))
68
+
69
+ return result
70
+
71
+
72
+ def find_diff(obj1: ET.Element, obj2: ET.Element, tag_key: str = "id"):
73
+ """Compare *obj1* and *obj2*, returning a minimal diff result.
74
+
75
+ Args:
76
+ obj1: First XML element tree to compare.
77
+ obj2: Second XML element tree to compare.
78
+ tag_key: Attribute used to build unique element paths (e.g. "id", "name"). Defaults to "id".
79
+
80
+ Returns:
81
+ A tuple of (all_paths, paths1, paths2, common, only1, only2, total_attr_diffs).
82
+ """
83
+ paths1 = collect_paths(obj1, tag_key=tag_key)
84
+ paths2 = collect_paths(obj2, tag_key=tag_key)
85
+
86
+ set1 = set(paths1.keys())
87
+ set2 = set(paths2.keys())
88
+ common = set1 & set2
89
+ only1 = sorted(set1 - set2)
90
+ only2 = sorted(set2 - set1)
91
+ all_paths = sorted(set1 | set2)
92
+
93
+ total_attr_diffs = 0
94
+ for path in common:
95
+ e1, e2 = paths1[path], paths2[path]
96
+ for attr in set(e1.attrib) | set(e2.attrib):
97
+ if e1.get(attr) != e2.get(attr):
98
+ total_attr_diffs += 1
99
+
100
+ return all_paths, paths1, paths2, common, only1, only2, total_attr_diffs
101
+
102
+
103
+ # ----- Report -----
104
+
105
+
106
+ def build_report(obj1: ET.Element, obj2: ET.Element, tag_key: str = "id") -> str:
107
+ """Compare *obj1* and *obj2*; return the full report as a single string.
108
+
109
+ Args:
110
+ obj1: First XML element tree to compare.
111
+ obj2: Second XML element tree to compare.
112
+ tag_key: Attribute used to build unique element paths (e.g. "id", "name"). Defaults to "id".
113
+
114
+ Returns:
115
+ The formatted diff report as a single string.
116
+ """
117
+ all_paths, paths1, paths2, common, only1, only2, total_attr_diffs = find_diff(obj1, obj2, tag_key)
118
+
119
+ if not all_paths:
120
+ return "Both objects are empty, so there is nothing to compare."
121
+
122
+ sep = "-" * 45
123
+
124
+ # Report summary.
125
+ lines: list[str] = [
126
+ "===== XML OBJECT COMPARISON REPORT =====",
127
+ "",
128
+ "REPORT SUMMARY",
129
+ sep,
130
+ f" Total tags : {len(all_paths)}",
131
+ f" Total tags in object 1 : {len(paths1)}",
132
+ f" Total tags in object 2 : {len(paths2)}",
133
+ f" Total common/shared tags : {len(common)}",
134
+ f" Total tags only in object 1 : {len(only1)}",
135
+ f" Total tags only in object 2 : {len(only2)}",
136
+ f" Total unique/non-shared tags : {len(only1) + len(only2)}",
137
+ f" Total attribute differences : {total_attr_diffs}",
138
+ "",
139
+ ]
140
+
141
+ # Tag-level differences.
142
+ lines += ["TAG DIFFERENCES", sep]
143
+ if not only1 and not only2:
144
+ lines.append(" Both objects have exactly the same tags.")
145
+ else:
146
+ if only1:
147
+ lines.append(" Tags present in object 1 but NOT in object 2:")
148
+ lines += [f" \u2022 {p.lstrip('/')}" for p in only1]
149
+ if only2:
150
+ lines.append(" Tags present in object 2 but NOT in object 1:")
151
+ lines += [f" \u2022 {p.lstrip('/')}" for p in only2]
152
+ lines.append("")
153
+
154
+ # Attribute-level differences.
155
+ lines += ["ATTRIBUTE DIFFERENCES", sep]
156
+ any_diff = False
157
+ level_map: dict[int, list[str]] = defaultdict(list)
158
+ for p in all_paths:
159
+ level_map[p.count("/")].append(p)
160
+
161
+ for depth in sorted(level_map.keys()):
162
+ for path in level_map[depth]:
163
+ e1 = paths1.get(path)
164
+ e2 = paths2.get(path)
165
+
166
+ if e1 is None or e2 is None:
167
+ continue
168
+
169
+ # Compare attributes one by one.
170
+ attr_diffs: list[str] = []
171
+ for attr in sorted(set(e1.attrib.keys()) | set(e2.attrib.keys())):
172
+ v1, v2 = e1.get(attr), e2.get(attr)
173
+ if v1 != v2:
174
+ attr_diffs.append(f" {attr}: obj1={v1!r} obj2={v2!r}")
175
+
176
+ if attr_diffs:
177
+ any_diff = True
178
+ lines.append(f" {path.lstrip('/')}")
179
+ lines.extend(attr_diffs)
180
+ lines.append("")
181
+
182
+ if not any_diff:
183
+ lines += [" Both elements are exactly the same.", ""]
184
+
185
+ lines += ["===== END OF REPORT ====="]
186
+ return "\n".join(lines)
187
+
188
+
189
+ def save_report(report: str, report_path: str) -> None:
190
+ """Save the report to a file."""
191
+ with open(report_path, "w", encoding="utf-8") as fh:
192
+ fh.write(report)
193
+ fh.write("\n")
194
+
195
+
196
+ # ----- Main: shows an example of how to use the script. -----
197
+
198
+
199
+ def main() -> None:
200
+ """Entry point: compare two XML/text files and save the diff report to an output file.
201
+
202
+ Optional flag:
203
+ --tag-key=<attr> Attribute used to disambiguate sibling elements in the path map (default: "id").
204
+ Example: --tag-key=name
205
+ """
206
+ # Extract --tag-key=<value> flag from argv before positional parsing.
207
+ tag_key = "id"
208
+ filtered_argv = []
209
+ for arg in sys.argv[1:]:
210
+ if arg.startswith("--tag-key="):
211
+ tag_key = arg.split("=", 1)[1]
212
+ else:
213
+ filtered_argv.append(arg)
214
+
215
+ if len(filtered_argv) < 2:
216
+ print("Usage: python xml_diff.py <file1.xml|file1.txt> <file2.xml|file2.txt> [output.txt] [--tag-key=<attr>]")
217
+ sys.exit(1)
218
+
219
+ file1 = filtered_argv[0]
220
+ file2 = filtered_argv[1]
221
+ report_path = filtered_argv[2] if len(filtered_argv) > 2 else "output.txt"
222
+
223
+ try:
224
+ print(f"Parsing {file1}...")
225
+ elements1 = parse_file(file1)
226
+ except FileNotFoundError:
227
+ print(f"Error: file not found — {file1}")
228
+ sys.exit(1)
229
+ except ET.ParseError as exc:
230
+ print(f"Error: could not parse XML — {exc}")
231
+ sys.exit(1)
232
+
233
+ try:
234
+ print(f"Parsing {file2}...")
235
+ elements2 = parse_file(file2)
236
+ except FileNotFoundError:
237
+ print(f"Error: file not found — {file2}")
238
+ sys.exit(1)
239
+ except ET.ParseError as exc:
240
+ print(f"Error: could not parse XML — {exc}")
241
+ sys.exit(1)
242
+
243
+ # Display the parsed elements.
244
+ display_elements(elements1)
245
+ display_elements(elements2)
246
+
247
+ # Find the differences and build a report.
248
+ report = build_report(elements1, elements2, tag_key)
249
+
250
+ # Print the report to the console.
251
+ print(report)
252
+
253
+ # Save the report to a file.
254
+ save_report(report, report_path)
255
+ print(f"\nReport saved to: {report_path}")
256
+
257
+
258
+ if __name__ == "__main__":
259
+ main()
@@ -0,0 +1,163 @@
1
+ """
2
+ xml_parser.py — Parse an XML/text file into ET.Element objects,
3
+ stripping comments and other non-element constructs before parsing.
4
+
5
+ Pre-processing pipeline (applied in order):
6
+ 1. strip_comments — removes <!-- ... -->
7
+ 2. strip_doctype — removes <!DOCTYPE ... [ ... ]>
8
+ 3. strip_processing_instructions — removes <?foo ... ?> (keeps <?xml ...?>)
9
+ 4. strip_xml_declaration — removes <?xml ...?> (safe to wrap in root)
10
+ 5. strip_entity_refs — removes custom &entity; references
11
+
12
+ Python: 3.12
13
+ Author: Wing Kui, Tsoi
14
+ Coauthor: AI
15
+ Last Updated: 2026-11-30
16
+ """
17
+
18
+ import re
19
+ import sys
20
+ import xml.etree.ElementTree as ET
21
+
22
+
23
+ # ----- Pre-processing helpers -----
24
+
25
+
26
+ def strip_comments(content: str) -> str:
27
+ """Remove XML comments: <!-- ... -->"""
28
+ return re.sub(r"<!--.*?-->", "", content, flags=re.DOTALL)
29
+
30
+
31
+ def strip_doctype(content: str) -> str:
32
+ """Remove DOCTYPE declaration including optional internal DTD subset [...].
33
+
34
+ Uses [^[>]* to skip the keyword/identifiers before the optional subset,
35
+ avoiding accidental matches on '>' characters inside the subset.
36
+ """
37
+ return re.sub(r"<!DOCTYPE\b[^[>]*(?:\[[^\]]*\])?\s*>", "", content, flags=re.DOTALL)
38
+
39
+
40
+ def strip_processing_instructions(content: str) -> str:
41
+ """Remove processing instructions (<?...?>) except the XML declaration."""
42
+ return re.sub(r"<\?(?!xml\b).*?\?>", "", content, flags=re.DOTALL)
43
+
44
+
45
+ def strip_xml_declaration(content: str) -> str:
46
+ """Remove the XML declaration (<?xml ...?>) from the start of a document.
47
+
48
+ Required before wrapping content in a synthetic root element,
49
+ since an XML declaration is only valid at the very start of a document.
50
+ """
51
+ return re.sub(r"^\s*<\?xml\b.*?\?>", "", content, flags=re.DOTALL)
52
+
53
+
54
+ def strip_entity_refs(content: str) -> str:
55
+ """Remove custom named entity references (&foo;), preserving built-in XML entities."""
56
+ builtin = {"amp", "lt", "gt", "apos", "quot"}
57
+ return re.sub(
58
+ r"&([a-zA-Z_][a-zA-Z0-9._-]*);",
59
+ lambda m: m.group(0) if m.group(1) in builtin else "",
60
+ content,
61
+ )
62
+
63
+
64
+ def preprocess(content: str) -> str:
65
+ """Apply the full pre-processing pipeline to raw file content."""
66
+ content = strip_comments(content)
67
+ content = strip_doctype(content)
68
+ content = strip_processing_instructions(content)
69
+ content = strip_xml_declaration(content)
70
+ content = strip_entity_refs(content)
71
+ return content
72
+
73
+
74
+ # ----- Namespace handling -----
75
+
76
+
77
+ def strip_namespaces(element: ET.Element) -> None:
78
+ """Strip namespace URIs from tag names and attribute keys, in-place, for easy queries."""
79
+ if "}" in element.tag:
80
+ element.tag = element.tag.split("}", 1)[1]
81
+ element.attrib = {
82
+ (k.split("}", 1)[1] if "}" in k else k): v
83
+ for k, v in element.attrib.items()
84
+ }
85
+ for child in element:
86
+ strip_namespaces(child)
87
+
88
+
89
+ # ----- Parsing -----
90
+
91
+
92
+ def parse_file(file_path: str) -> list[ET.Element]:
93
+ """Read and parse a file, returning a list of top-level ET.Element objects.
94
+
95
+ Files with multiple root-level elements are supported by wrapping the
96
+ content in a temporary <_root_> element before parsing,
97
+ then returning its children.
98
+ """
99
+ with open(file_path, "r", encoding="utf-8") as fh:
100
+ content = fh.read()
101
+
102
+ content = preprocess(content)
103
+ wrapped = ET.fromstring(f"<_root_>{content}</_root_>")
104
+ elements = list(wrapped)
105
+ for element in elements:
106
+ strip_namespaces(element)
107
+ return elements
108
+
109
+
110
+ # ----- Output -----
111
+
112
+
113
+ def display_elements(elements: list[ET.Element]) -> None:
114
+ """Print each XML element to stdout with 2-space indentation."""
115
+ for element in elements:
116
+ ET.indent(element, space=" ")
117
+ print(ET.tostring(element, encoding="unicode"))
118
+
119
+
120
+ def save_elements_to_file(elements: list[ET.Element], file_path: str = "output.txt") -> None:
121
+ """Save formatted XML elements to a file."""
122
+ with open(file_path, "w", encoding="utf-8") as fh:
123
+ for element in elements:
124
+ ET.indent(element, space=" ")
125
+ fh.write(ET.tostring(element, encoding="unicode"))
126
+ fh.write("\n")
127
+
128
+
129
+ # ----- Main: shows an example of how to use the script. -----
130
+
131
+
132
+ def main() -> None:
133
+ """Entry point: parse an XML/text file from argv and save elements to an output file."""
134
+ if len(sys.argv) < 2:
135
+ print("Usage: python xml_parser.py <file.xml|file.txt> [output.txt]")
136
+ sys.exit(1)
137
+
138
+ file_path = sys.argv[1]
139
+ output_file = sys.argv[2] if len(sys.argv) > 2 else "output.txt"
140
+
141
+ try:
142
+ print(f"Parsing {file_path}...")
143
+ elements = parse_file(file_path)
144
+ except FileNotFoundError:
145
+ print(f"Error: file not found — {file_path}")
146
+ sys.exit(1)
147
+ except ET.ParseError as exc:
148
+ print(f"Error: could not parse XML — {exc}")
149
+ sys.exit(1)
150
+
151
+ # Display the parsed elements.
152
+ print()
153
+ display_elements(elements)
154
+ print(f"Parsed {len(elements)} XML root element(s)")
155
+ print(f"Element(s): {elements}")
156
+
157
+ # Save the parsed elements to a file.
158
+ save_elements_to_file(elements, output_file)
159
+ print(f"Element(s) saved to {output_file}")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: xml-checker
3
+ Version: 1.0.0
4
+ Summary: A Python toolkit for parsing and comparing XML files.
5
+ Author: Wing Kui Tsoi
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wingkuitsoi/xml-checker
8
+ Project-URL: Repository, https://github.com/wingkuitsoi/xml-checker
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Text Processing :: Markup :: XML
13
+ Requires-Python: >=3.12
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # xml-checker
19
+
20
+ A Python toolkit for parsing and comparing XML files.
21
+
22
+ ## Overview
23
+
24
+ | Script | Purpose |
25
+ |--------|---------|
26
+ | `xml_parser.py` | Parse XML/text files into `ET.Element` objects with robust pre-processing |
27
+ | `xml_diff.py` | Compare two parsed XML objects and produce a structured diff report |
28
+
29
+ ## Requirements
30
+
31
+ - Python 3.12+
32
+ - Standard library only (no third-party dependencies)
33
+
34
+ ---
35
+
36
+ ## xml_parser.py
37
+
38
+ Reads an XML or text file and returns a list of top-level `ET.Element` objects.
39
+ Files with multiple root-level elements are supported by wrapping content in a temporary `<_root_>` element before parsing.
40
+
41
+ **Pre-processing pipeline** (applied in order before parsing):
42
+
43
+ | Step | What is removed |
44
+ |------|----------------|
45
+ | 1 | `<!-- comments -->` |
46
+ | 2 | `<!DOCTYPE ...>` declarations (including internal DTD subsets) |
47
+ | 3 | Processing instructions `<?...?>` (the XML declaration `<?xml ...?>` is kept until step 4) |
48
+ | 4 | XML declaration `<?xml ...?>` |
49
+ | 5 | Custom `&entity;` references (built-ins `&amp;`, `&lt;`, `&gt;`, `&apos;`, `&quot;` are preserved) |
50
+
51
+ Namespace URIs are stripped from all tag names and attribute keys after parsing.
52
+
53
+ ### CLI
54
+
55
+ ```
56
+ python xml_parser.py <file.xml|file.txt> [output.txt]
57
+ ```
58
+
59
+ Output file defaults to `output.txt`.
60
+
61
+ ### Python API
62
+
63
+ ```python
64
+ from xml_parser import parse_file, display_elements, save_elements_to_file
65
+
66
+ elements = parse_file("input.xml") # list[ET.Element]
67
+ display_elements(elements) # print to stdout
68
+ save_elements_to_file(elements, "out.txt") # write to file
69
+ ```
70
+
71
+ ---
72
+
73
+ ## xml_diff.py
74
+
75
+ Compares two XML objects and generates a detailed diff report covering:
76
+
77
+ - **Summary** – total tags, tags exclusive to each object, common tags, and total attribute differences.
78
+ - **Tag differences** – element paths present in one object but not the other.
79
+ - **Attribute differences** – per-element, per-attribute value comparison (grouped by depth level).
80
+
81
+ ### CLI
82
+
83
+ ```
84
+ python xml_diff.py <file1.xml|file1.txt> <file2.xml|file2.txt> [output.txt] [--tag-key=<attr>]
85
+ ```
86
+
87
+ | Argument | Required | Description |
88
+ |----------|----------|-------------|
89
+ | `file1` | Yes | First XML file |
90
+ | `file2` | Yes | Second XML file |
91
+ | `output.txt` | No | Report output path (default: `output.txt`) |
92
+ | `--tag-key=<attr>` | No | Attribute used to disambiguate sibling elements in paths (default: `id`) |
93
+
94
+ ### Python API
95
+
96
+ ```python
97
+ from xml_parser import parse_file
98
+ from xml_diff import build_report, save_report
99
+
100
+ obj1 = parse_file("a.xml")
101
+ obj2 = parse_file("b.xml")
102
+
103
+ report = build_report(obj1, obj2, tag_key="id")
104
+ print(report)
105
+ save_report(report, "output.txt")
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Sample Files
111
+
112
+ The `samples/` folder contains example files organised by use case.
113
+
114
+ ### Parser samples — `samples/parser/`
115
+
116
+ | Input | Expected output | Description |
117
+ |-------|----------------|-------------|
118
+ | `simple.xml` | `simple_output.txt` | Basic XML with nested elements and attributes |
119
+ | `complex.xml` | `complex_output.txt` | Demonstrates all pre-processing: comments, DOCTYPE, processing instructions, namespaces, and entity references |
120
+
121
+ ```
122
+ python xml_parser.py samples/parser/simple.xml samples/parser/simple_output.txt
123
+ python xml_parser.py samples/parser/complex.xml samples/parser/complex_output.txt
124
+ ```
125
+
126
+ ### Diff samples — `samples/diff/`
127
+
128
+ | File pair | Expected report | Scenario |
129
+ |-----------|----------------|----------|
130
+ | `empty_a.xml` / `empty_b.xml` | `empty_report.txt` | Both files contain no XML elements → `"Both objects are empty, so there is nothing to compare."` |
131
+ | `same_a.xml` / `same_b.xml` | `same_report.txt` | Identical XML structure and attributes → no differences reported |
132
+ | `different_a.xml` / `different_b.xml` | `different_report.txt` | Server configs with differing hosts, ports, drivers, and feature sets → full diff report |
133
+
134
+ ```
135
+ python xml_diff.py samples/diff/empty_a.xml samples/diff/empty_b.xml samples/diff/empty_report.txt
136
+ python xml_diff.py samples/diff/same_a.xml samples/diff/same_b.xml samples/diff/same_report.txt
137
+ python xml_diff.py samples/diff/different_a.xml samples/diff/different_b.xml samples/diff/different_report.txt
138
+ ```
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ xml_checker/__init__.py
5
+ xml_checker/xml_diff.py
6
+ xml_checker/xml_parser.py
7
+ xml_checker.egg-info/PKG-INFO
8
+ xml_checker.egg-info/SOURCES.txt
9
+ xml_checker.egg-info/dependency_links.txt
10
+ xml_checker.egg-info/entry_points.txt
11
+ xml_checker.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ xml-diff = xml_checker.xml_diff:main
3
+ xml-parser = xml_checker.xml_parser:main
@@ -0,0 +1 @@
1
+ xml_checker