#!/usr/bin/env python
"""
Script to extract and display the structure of an XML file.

It take the XML file as single argument.

Can be used if the script "identify-xml-structure.sh" cannot
parse the file due to its large size.

Sources & credits:
    https://python-forum.io/thread-6204.html
    https://stackoverflow.com/a/11850445
"""
import re, collections, sys
from lxml import etree
from lxml.etree import XMLParser, parse

tree = parse(sys.argv[1], parser=XMLParser(huge_tree=True))
xml_root = tree.getroot()
raw_tree = etree.ElementTree(xml_root)
nice_tree = collections.OrderedDict()
 
for tag in xml_root.iter():
    path = re.sub(r'\[[0-9]+\]', '', raw_tree.getpath(tag))
    if path not in nice_tree:
        nice_tree[path] = []
    if len(tag.keys()) > 0:
        nice_tree[path].extend(attrib for attrib in tag.keys() if attrib not in nice_tree[path])            
 
for path, attribs in nice_tree.items():
    indent = int(path.count('/') - 1)
    print('{0}{1}: {2} [{3}]'.format('  ' * indent, indent, path.split('/')[-1], ', '.join(attribs) if len(attribs) > 0 else '-'))