with open("xmlbasic.txt") as lines_file:
lines = lines_file.read()
import xml.etree.ElementTree as ET
root = ET.Element('root')
for line in lines:
head, subhead, tail = line.split(":")
head_branch = root.find(head)
if not head_branch:
head_branch = ET.SubElement(root, head)
subhead_branch = head_branch.find(subhead)
if not subhead_branch:
subhead_branch = ET.SubElement(branch1, subhead)
subhead_branch.text = tail
tree = ET.ElementTree(root)
ET.dump(tree)
Логика проста - вы уже высказали это в своем вопросе!Вам просто нужно проверить, существует ли ветвь в дереве, прежде чем создавать его.
Обратите внимание, что это, вероятно, неэффективно, так как вы ищете все дерево для каждой строки.Это потому, что ElementTree
не предназначен для уникальности.
Если вам требуется скорость (что может и не понадобиться, особенно для небольших деревьев!), Более эффективным способом было бы использовать defaultdict
для хранения древовидной структуры перед преобразованием ее в ElementTree
.
import collections
import xml.etree.ElementTree as ET
with open("xmlbasic.txt") as lines_file:
lines = lines_file.read()
root_dict = collections.defaultdict( dict )
for line in lines:
head, subhead, tail = line.split(":")
root_dict[head][subhead] = tail
root = ET.Element('root')
for head, branch in root_dict.items():
head_element = ET.SubElement(root, head)
for subhead, tail in branch.items():
ET.SubElement(head_element,subhead).text = tail
tree = ET.ElementTree(root)
ET.dump(tree)