Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert plain text list to html

Tags:

html

parsing

ruby

I have a plain text list like this:

I am the first top-level list item
  I am his son
  Me too
Second one here
  His son
  His daughter
    I am the son of the one above
    Me too because of the indentation
  Another one

And I would like to turn that into:

<ul>
  <li>I am the first top-level list-item
    <ul>
      <li>I am his son</li>
      <li>Me too</li>
    </ul>
  </li>
  <li>Second one here
    <ul>
      <li>His son</li>
      <li>His daughter
        <ul>
          <li>I am the son of the one above</li>
          <li>Me too because of the indentation</li>
        </ul>
      </li>
      <li>Another one</li>
    </ul>
  </li>
</ul>

How would one go about doing that?

like image 322
morbusg Avatar asked May 16 '26 04:05

morbusg


1 Answers

I never used ruby but the usual algorithm stays the same:

  1. Create a data structure like this:
    Node => (Text => string, Children => array of Nodes)
  2. Read a line
  3. Check if indent is higher than current indent
  4. If yes, append the Line to the Children of the current Node and call the method recursively with the node as active. Continue from 2.
  5. Check if indent is equal to current indent.
  6. If yes, append the line to the active node. Continue from 2.
  7. Check if the indent is lower than the current indent.
  8. If yes, return from the method.
  9. Repeat until EOF.

For output:

1. print <ul>
2. Take the first node, print <li>node.Text
3. If there are child nodes (count of node.Children > 0) recurse to 1.
4. print </li>
5. take next node, continue from 2.
6. print </ul>