1

我正在使用Text.ParserCombinators.ParsecandText.XHtml来解析输入并获得 HTML 输出。

如果我的输入是:

    * 第一项,第一级
    ** 第一项,第二级
    ** 第二项,二级
    * 第二项,一级

我的输出应该是:

<ul><li>First item, First level <ul><li>First item, Second level </li><li>Second item, Second level </li></ul></li><li>Second item, First level</li></ul>

我写了这个,但显然不能递归工作

list = do{ s <- many1 item;return (olist << s) }
item = do{ 
    (count 1 (char '*'))
    ;s <- manyTill anyChar newline
    ;return ( li <<  s)
  }

有任何想法吗?递归可以多于两个级别。
谢谢!

4

1 回答 1

2
list n = do first <- item n
            rest <- many $ try $ try (list (n+1)) <|> item n
            return $ ulist << (first : rest)

item n = do count n (char '*')
            s <- manyTill anyChar newline
            return $ li << s

现在parse (list 1) "foo" "* a\n** a 1\n** a 2\n* b\n** b 1\n** b 2\n"将返回您要求的内容。

但请注意,嵌套列表本身应该在 li 内,这样才能成为有效的 xhtml。

于 2010-04-24T17:48:10.090 回答