packages feed

panda-0.0.0.3: Panda/Helper/Escape.hs

module Panda.Helper.Escape where


import Text.XML.HaXml hiding ((!))
import Text.XML.HaXml.Parse (xmlParseWith, document)
import Text.XML.HaXml.Lex (xmlLex)



unescape :: String -> String
unescape = concatMap ctext . xmlUnEscapeContent stdXmlEscaper .
              unwrapTag .
              either error id . fst . xmlParseWith document .
              xmlLex "oops, lexer failed" . wrapWithTag "t"
  where
    ctext (CString _ txt _)         = txt
    ctext (CRef (RefEntity name) _) = '&' : name ++ ";" -- skipped by escaper
    ctext (CRef (RefChar num) _)    = '&' : '#' : show num ++ ";" -- ditto
    ctext _                 = error "oops, can't unescape non-cdata"
    wrapWithTag t s = concat ["<", t, ">", s, "</", t, ">"]
    unwrapTag (Document _ _ (Elem _ _ c) _) = c
    unwrapTag _                             = error "oops, not wrapped"