Skip to content

Instantly share code, notes, and snippets.

@davidhcefx
Last active September 4, 2026 12:39
Show Gist options
  • Select an option

  • Save davidhcefx/7da8ced9f3a882bd3d7fa0d9a2a77ca8 to your computer and use it in GitHub Desktop.

Select an option

Save davidhcefx/7da8ced9f3a882bd3d7fa0d9a2a77ca8 to your computer and use it in GitHub Desktop.
Merge multiple XML files into one. Two nodes are the same if they have the same names and attributes.
#! /usr/bin/python3
# SPDX-AI-Disclosure: ai-generated
# SPDX-AI-Model: claude-haiku-4.5
# SPDX-AI-Provider: Anthropic
# SPDX-AI-Scope: Implementation only; human debugged and tested.
"""
Merge multiple XML files into one.
Two nodes are the same if they have the same names and attributes.
"""
from typing import Optional
import xml.etree.ElementTree as ET
import copy
from os import path
import sys
def elements_match(elem1: ET.Element, elem2: ET.Element) -> bool:
"""Check if two elements have the same tag name and attributes."""
if elem1.tag != elem2.tag:
return False
return elem1.attrib == elem2.attrib
def merge_element(target: ET.Element, source: ET.Element) -> None:
"""Recursively merge source element's children into target element.
For each child in source:
- If a matching child (same tag and attributes) exists in target, recursively merge
- Otherwise, deep copy and append the source child to target
"""
# print(f"Iterating source: {source.tag} {source.attrib}", file=sys.stderr)
for source_child in source:
# Look for a matching child in target with same tag and attributes
matching_child = None
for target_child in target:
if elements_match(source_child, target_child):
matching_child = target_child
break
# print(f"Child element {'not found' if matching_child is None else 'found'}: {source_child.tag} {source_child.attrib}", file=sys.stderr)
if matching_child is not None:
# Recursively merge the matching child
merge_element(matching_child, source_child)
else:
# No matching child found, deep copy and append
target.append(copy.deepcopy(source_child))
def merge_xml(files: list[str]) -> Optional[ET.ElementTree]:
if len(files) == 0:
return None
if not path.exists(files[0]):
print(f"File {files[0]} does not exist, skipping.", file=sys.stderr)
return merge_xml(files[1:])
tree = ET.parse(files[0])
root = tree.getroot()
for file in files[1:]:
if not path.exists(file):
print(f"File {file} does not exist, skipping.", file=sys.stderr)
continue
tree_to_merge = ET.parse(file)
root_to_merge = tree_to_merge.getroot()
# Only merge if roots have the same tag name and attributes
if elements_match(root, root_to_merge):
merge_element(root, root_to_merge)
else:
print(f"Cannot merge {file}: different root: {root.tag}, {root.attrib}", file=sys.stderr)
return tree
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: {} input_files...".format(sys.argv[0]), file=sys.stderr)
raise SystemExit(1)
input_files = sys.argv[1:]
merged_tree = merge_xml(input_files)
if merged_tree is not None:
merged_tree.write(sys.stdout.buffer, xml_declaration=True, encoding="utf-8")
@davidhcefx

davidhcefx commented Sep 4, 2026 •

Copy link
Copy Markdown
Author

Example Testcase

a.xml

<?xml version='1.0' encoding='utf-8'?>
<coverage version="1">
  <file path="hello_world.c">
    <lineToCover lineNumber="24" covered="true"/>
    <lineToCover lineNumber="26" covered="true"/>
  </file>
  <file path="foo.c">
    <lineToCover lineNumber="15" covered="true"/>
    <lineToCover lineNumber="18" covered="true"/>
  </file>
</coverage>

b.xml

<?xml version='1.0' encoding='utf-8'?>
<coverage version="1">
  <file path="hello_world.c">
    <lineToCover lineNumber="28" covered="false"/>
    <lineToCover lineNumber="30" covered="false"/>
  </file>
  <file path="foo.c">
    <lineToCover lineNumber="20" covered="false"/>
    <lineToCover lineNumber="22" covered="true"/>
  </file>
</coverage>

Output

<?xml version='1.0' encoding='utf-8'?>
<coverage version="1">
  <file path="hello_world.c">
    <lineToCover lineNumber="24" covered="true" />
    <lineToCover lineNumber="26" covered="true" />
  <lineToCover lineNumber="28" covered="false" />
    <lineToCover lineNumber="30" covered="false" />
  </file>
  <file path="foo.c">
    <lineToCover lineNumber="15" covered="true" />
    <lineToCover lineNumber="18" covered="true" />
  <lineToCover lineNumber="20" covered="false" />
    <lineToCover lineNumber="22" covered="true" />
  </file>
</coverage>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment