Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from xml.etree import ElementTree as ET
import re

li = ['1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/']
li = sorted(li)
# In Python >= 3.6 dicts maintain order
# Sets don't? So use best of both worlds, dict: speed and order
di = {l: False for l in li}

root = ET.Element('root')

# First build the root nodes, remove them from dict
for p in list(di.keys()):
  if len(list(filter(None, p.split('/')))) == 1:
    del di[p]
    root.append(ET.Element('include', {'path': p}))

# Because dict (and so keys()) are ordered, we can assume that the nodes higher 
# in the include tree are created before the more in-depth ones
for p in list(di.keys()):
  parent_path = re.sub('\d+\/$', '', p)
  try:
    parent = root.find(f'.//include[@path="{parent_path}"]')
    parent.append(ET.Element('include', {'path': p}))
  except Exception:
    print(f"parent not found for {p}")

print(ET.tostring(root))
Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux