import xml.etree.ElementTree as ET
from graphviz import Digraph
import os
import argparse
def add_nodes(element, dot, include_text=True, max_text_length=20, parent_id=None):
"""
Recursively add nodes to the Graphviz Digraph.
Each node represents an XML element.
"""
# Generate a unique ID for the element based on its memory address
current_id = str(id(element))
# Build the node label
label = f"Tag: {element.tag}"
# Add attributes if present
if element.attrib:
label += "\nAttributes:"
for k, v in element.attrib.items():
label += f"\n{k}={v}"
# Add text content if enabled and present
if include_text and element.text:
text = element.text.strip()
if text:
if len(text) > max_text_length:
text = text[:max_text_length] + "..."
label += f"\nText: {text}"
# Add the node to the graph
dot.node(current_id, label)
# Connect to the parent node if it exists
if parent_id:
dot.edge(parent_id, current_id)
# Recursively add child elements
for child in element:
add_nodes(child, dot, include_text, max_text_length, current_id)
def visualise_xml(
xml_file,
output_file='xml_structure',
view=True,
include_text=True,
max_text_length=20
):
"""
Parses an XML file and visualizes its structure using Graphviz.
Parameters:
- xml_file (str): Path to the XML file.
- output_file (str): Output file name (without extension) for the rendered graph.
- view (bool): Whether to open the generated file after rendering.
- include_text (bool): Whether to include text content in node labels.
- max_text_length (int): Maximum characters to show for text content before truncating.
"""
# Parse the XML file
tree = ET.parse(xml_file)
root = tree.getroot()
# Create a directed graph for hierarchical XML structure
dot = Digraph(comment='XML Document Structure')
# Set graph attributes for the document background
dot.graph_attr.update(
pad='1', # Set padding around the graph
margin='0' # Remove margins to fill the page
)
# Start the recursive node addition from the root element
add_nodes(root, dot, include_text, max_text_length)
# Render the graph to a file (default format: PDF)
dot.render(f'{output_file}.gv', format='pdf', view=view)
return dot
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Visualize XML structure using Graphviz.')
parser.add_argument('input_file', help='Path to the input XML file')
parser.add_argument('--output', '-o', default='xml_structure',
help='Output file name without extension (default: xml_structure)')
parser.add_argument('--no-view', action='store_false', dest='view',
help='Disable opening the rendered file automatically')
parser.add_argument('--no-text', action='store_false', dest='include_text',
help='Exclude text content from node labels')
parser.add_argument('--max-text-len', type=int, default=20, dest='max_text_length',
help='Maximum text length to display before truncating (default: 20)')
args = parser.parse_args()
if not os.path.exists(args.input_file):
raise FileNotFoundError(f"XML file not found: {args.input_file}")
try:
visualise_xml(
xml_file=args.input_file,
output_file=args.output,
view=args.view,
include_text=args.include_text,
max_text_length=args.max_text_length
)
except ET.ParseError as e:
raise ValueError(f"Error parsing input file: {e}")