Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>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) </code></pre> <p>The logic is simple -- you already stated it in your question! You merely need to check whether a branch already exists in the tree before creating it.</p> <p>Note that this is likely inefficient, since you are searching up to the entire tree for each line. This is because <code>ElementTree</code> is not designed for uniqueness. </p> <hr> <p>If you require speed (which you may not, especially for smallish trees!), a more efficient way would be to use a <code>defaultdict</code> to store the tree structure before converting it to an <code>ElementTree</code>.</p> <pre><code>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) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload