我有一个像这样的纯文本列表:
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>
怎么会去做呢?
最佳答案
此代码确实按预期工作,但标题打印在新行上。
require "rubygems"
require "builder"
def get_indent(line)
line.to_s =~ /(\s*)(.*)/
$1.size
end
def create_list(lines, list_indent = -1,
b = Builder::XmlMarkup.new(:indent => 2, :target => $stdout))
while not lines.empty?
line_indent = get_indent lines.first
if line_indent == list_indent
b.li {
b.text! lines.shift.strip + $/
if get_indent(lines.first) > line_indent
create_list(lines, line_indent, b)
end
}
elsif line_indent < list_indent
break
else
b.ul {
create_list(lines, line_indent, b)
}
end
end
end
关于html - 将纯文本列表转换为 html,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2873799/