XML to Tree

Given a valid XML document, convert an XML string to an n-ary tree.


Given a valid XML document, construct a tree structure that correctly represents the hierarchical relations between the nodes in the XML document.

As support, an XML Node class is defined in the lesson. Each node stores the name of the node and, the list of its child nodes. We will not store XML attributes, only the name of the node.

Additionally, an XML Tokenizer class is also provided. This class implements the Get Next Element function that can be called in a loop to return all the XML tokens in the string, classified as one of:

  • Element opening tag
  • Element closing tag
  • Element text
  • Unknown element (a catch-all for unrecognized tokens)


Let’s consider the XML document below:

        <h2>Chapter 1</h2>
        <h3>Chapter 2</h3>
        <h4>Chapter 2.1</h4>

For the above HTML (we could use any XML document), here is the output tree:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.