modify code to only display top level child element. import xml.etree.ElementTree as ET
from graphviz import Digraph
import os
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
Example usage
if name == "main":
input_file = "/home/kali/Documents/NAPS/DiGraph/test_1.xml"
if not os.path.exists(input_file):
raise FileNotFoundError(f"XML file not found: {input_file}")
try:
visualise_xml(input_file, include_text=True)
except ET.ParseError as e:
raise ValueError(f"Error parsing input file: {e}")