Created
August 21, 2011 07:18
-
-
Save snoyberg/1160282 to your computer and use it in GitHub Desktop.
Convert xml-enumerator values to blaze-html values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Text.XML.Xml2Html () where | |
import qualified Text.XML.Enumerator.Resolved as X | |
import qualified Text.Blaze as B | |
import qualified Text.Blaze.Html5 as B5 | |
import qualified Text.Blaze.Internal as BI | |
import qualified Data.Text as T | |
import Data.String (fromString) | |
import Data.Monoid (mempty) | |
import Data.List (foldl') | |
import Text.Blaze.Renderer.String (renderHtml) | |
import System.Environment (getArgs) | |
import qualified Data.Set as Set | |
main = do | |
[x] <- getArgs | |
doc <- X.readFile_ x X.decodeEntities | |
putStrLn $ renderHtml $ B.toHtml doc | |
instance B.ToHtml X.Document where | |
toHtml (X.Document _ root _) = B5.docType >> B.toHtml root | |
instance B.ToHtml X.Element where | |
toHtml (X.Element name' attrs children) = | |
if isVoid | |
then foldl' (B.!) leaf attrs' | |
else foldl' (B.!) parent attrs' $ mapM_ B.toHtml children | |
where | |
isVoid = X.nameLocalName name' `Set.member` voidElems | |
parent :: B.Html -> B.Html | |
parent = BI.Parent tag open close | |
leaf :: B.Html | |
leaf = BI.Leaf tag open (fromString " />") | |
name = T.unpack $ X.nameLocalName name' | |
tag = fromString name | |
open = fromString $ '<' : name | |
close = fromString $ concat ["</", name, ">"] | |
attrs' :: [B.Attribute] | |
attrs' = map goAttr attrs | |
toTag = B.textTag . X.nameLocalName | |
goAttr (key, value) = B.customAttribute (toTag key) $ B.toValue value | |
instance B.ToHtml X.Node where | |
toHtml (X.NodeElement e) = B.toHtml e | |
toHtml (X.NodeContent t) = B.toHtml t | |
toHtml _ = mempty | |
voidElems :: Set.Set T.Text | |
voidElems = Set.fromAscList $ T.words $ T.pack "area base br col command embed hr img input keygen link meta param source track wbr" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment