module Text.XML.HaXml.Wrappers
( fix2Args
, processXmlWith
) where
import System
import IO
import List (isSuffixOf)
import Text.XML.HaXml.Types (Document(..),Content(..))
import Text.XML.HaXml.Combinators (CFilter)
import Text.XML.HaXml.Parse (xmlParse)
import Text.XML.HaXml.Html.Parse (htmlParse)
import Text.XML.HaXml.Pretty as PP(document)
import Text.PrettyPrint.HughesPJ (render)
fix2Args :: IO (String,String)
fix2Args = do
args <- getArgs
case length args of
0 -> return ("-", "-")
1 -> return (args!!0, "-")
2 -> return (args!!0, args!!1)
_ -> do prog <- getProgName
putStrLn ("Usage: "++prog++" [xmlfile] [outfile]")
exitFailure
processXmlWith :: CFilter -> IO ()
processXmlWith f = do
(inf,outf) <- fix2Args
input <- if inf=="-" then getContents else readFile inf
o <- if outf=="-" then return stdout else openFile outf WriteMode
parse <- if ".html" `isSuffixOf` inf || ".htm" `isSuffixOf` inf
then return (htmlParse inf)
else return (xmlParse inf)
( hPutStrLn o . render . PP.document . onContent f . parse) input
hFlush o
where
onContent :: CFilter -> Document -> Document
onContent filter (Document p s e m) =
case filter (CElem e) of
[CElem e'] -> Document p s e' m
[] -> error "produced no output"
_ -> error "produced more than one output"