Search code examples
haskellparsecfb2

Parsing FB2(XML) in Haskell


Started to learn Haskell, I decided to get acquainted with Parsec, but there were problems. I'm trying to implement the parsing of the books in the format of FB2. On conventional tags ( text ) is good, but when the tag within a tag - does not work.

import Text.ParserCombinators.Parsec

data FB2Doc = Node String FB2Doc
            | InnText String
            deriving (Eq,Show)

parseFB2 :: GenParser Char st [FB2Doc]
parseFB2 = many test

test :: GenParser Char st FB2Doc
test = do name <- nodeStart
          value <- getvalue
          nodeEnd
          return $ Node name value

nodeStart = do char '<'
               name <- many (letter <|> digit <|> oneOf "-_")
               char '>'
               return name

nodeEnd = do string "</"
             many (letter <|> digit)
             char '>'
             spaces 
gettext = do x <- many (letter <|> digit <|> oneOf "-_")
             return $ InnText x 

getvalue = do (nodeStart >> test) <|> gettext <|> return (Node "" (InnText ""))
main = do
         print $ parse parseFB2 "" "<h1><a2>ge</a2></h1> <genre>history_russia</genre>"

Solution

  • I think you want this:

    getvalue = try test <|> gettext
    

    The try is needed for empty nodes: "<bla></bla>". test will consume the '<' of </bla>, and the try allows for backtracking.