Certainly! When dealing with complex XML files, especially those that may be malformed or contain invalid lines (e.g., mixed log output, corrupted data, etc.), we need a more robust strategy than just line-by-line validation.
✅ Goal:
Write Python code to clean complex XML files by removing invalid lines while preserving valid XML structure, even when elements span multiple lines.
🧠 Strategy:
- Attempt full parse first: Try parsing the entire XML file using
lxml.etree, which supports recovery from some types of malformed XML.
- If that fails:
- Use a line-by-line filtering approach, trying to reconstruct a valid document by skipping only problematic lines.
- Optionally use
lxml recover mode to salvage as much content as possible.
✅ Python Code: Strip Invalid Lines from Complex XML Files
from lxml import etree
import os
def is_valid_xml_snippet(snippet):
"""Check if a snippet of XML is well-formed."""
try:
parser = etree.XMLParser(recover=False)
etree.fromstring(snippet, parser=parser)
return True
except etree.XMLSyntaxError:
return False
except Exception:
return False
def clean_complex_xml_file(input_path, output_path):
"""
Clean an XML file by attempting to remove invalid lines,
and write the cleaned result to a new file.
"""
print(f"Attempting to clean XML file: {input_path}")
# First try to parse the whole file using lxml's recover mode
try:
parser = etree.XMLParser(recover=True, encoding='utf-8')
tree = etree.parse(input_path, parser)
print("XML parsed successfully using recover mode.")
print("Writing fully recovered XML to:", output_path)
tree.write(output_path, encoding='utf-8', xml_declaration=True)
return
except Exception as e:
print("Full parse failed even in recover mode. Falling back to line cleaning:", str(e))
# If that didn't work, read line by line and filter out invalid ones
with open(input_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
cleaned_lines = []
buffer = ''
for idx, line in enumerate(lines):
buffer += line
# Try parsing the current buffer
if buffer.strip() and buffer.count('<') == buffer.count('>'):
# Heuristic: equal brackets might indicate complete tag
try:
parser = etree.XMLParser(recover=False)
etree.fromstring(buffer, parser=parser)
# If successful, commit the buffer
cleaned_lines.append(line)
buffer = ''
except etree.XMLSyntaxError:
# Still invalid — discard the line and reset buffer
print(f"Invalid line skipped (line {idx+1}): {line[:50]}...")
buffer = ''
else:
# Possibly part of a multi-line element — keep buffering
continue
# Add any remaining buffer if it's empty or whitespace-only
if buffer.strip() == '':
pass
else:
print("Unfinished XML content at end of file. Discarding partial content.")
# Join cleaned lines and write to output
cleaned_content = ''.join(cleaned_lines)
try:
etree.fromstring(cleaned_content)
print("Cleaned XML is valid.")
except etree.XMLSyntaxError as e:
print("Final cleaned XML is still invalid:", str(e))
print("Consider manual review or further processing.")
with open(output_path, 'w', encoding='utf-8') as f:
f.write(cleaned_content)
print("Cleaned XML written to:", output_path)
# Example usage
if __name__ == "__main__":
input_file = "complex_input.xml"
output_file = "cleaned_output.xml"
if not os.path.exists(input_file):
print(f"Input file '{input_file}' not found.")
else:
clean_complex_xml_file(input_file, output_file)