Search⌘ K
AI Features

XML to Tree

Understand how to convert a valid XML document into an n-ary tree using a stack and XML tokenizer. Explore how to systematically parse XML tokens to create hierarchical nodes, focusing on element tags and text while handling tree construction with linear time and space complexity.

Statement

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)

Example

Let’s consider the XML document below:

 ...