将纯文本列表转换为html

mor*_*usg 3 html ruby parsing

我有一个这样的纯文本列表:

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

我想把它变成:

<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>
Run Code Online (Sandbox Code Playgroud)

怎么会这样做呢?

Mor*_*dur 5

我从未使用过ruby,但通常的算法保持不变:

  1. 创建如下数据结构:
    Node =>(Text => string,Children => Nodes数组)
  2. 读一行
  3. 检查缩进是否高于当前缩进
  4. 如果是,则将Line附加到当前节点的Children,并以节点为活动状态递归调用该方法.从2继续.
  5. 检查缩进是否等于当前缩进.
  6. 如果是,请将该行附加到活动节点.从2继续.
  7. 检查缩进是否低于当前缩进.
  8. 如果是,请从方法返回.
  9. 重复直到EOF.

输出:

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>
Run Code Online (Sandbox Code Playgroud)