From d40e499442851756f29c757b7f6fae4478a95a54 Mon Sep 17 00:00:00 2001 From: Alice BRENON <alice.brenon@ens-lyon.fr> Date: Fri, 12 Feb 2021 18:17:55 +0100 Subject: [PATCH] Clean commented-out code, expose functions to handle errors and prepare FromXML implementation --- lib/Text/InvisiXML/Namespace.hs | 16 +++++----------- lib/Text/XML/Light/Serializer.hs | 15 +++++++++++---- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/lib/Text/InvisiXML/Namespace.hs b/lib/Text/InvisiXML/Namespace.hs index 0cd7220..9449141 100644 --- a/lib/Text/InvisiXML/Namespace.hs +++ b/lib/Text/InvisiXML/Namespace.hs @@ -3,13 +3,12 @@ module Text.InvisiXML.Namespace ( uRI , prefix , ixml - --, at - --, to , addAttr + , getAttr , setChildren ) where ---import Data.PositionTree (Position(..)) +import Data.List (find) import Text.XML.Light (Attr(..), Content(..), Element(..), QName(..), add_attr) uRI :: String @@ -21,14 +20,6 @@ prefix = "ixml" ixml :: String -> QName ixml qName = QName {qName, qURI = Just uRI, qPrefix = Just prefix} -{- -at :: Position -> Attr -at (Position p) = Attr (ixml "at") (show p) - -to :: Position -> Attr -to (Position p) = Attr (ixml "to") (show p) --} - onContent :: (Element -> Element) -> Content -> Content onContent f (Elem e) = Elem (f e) onContent _ x = x @@ -36,5 +27,8 @@ onContent _ x = x addAttr :: Attr -> Content -> Content addAttr = onContent . add_attr +getAttr :: QName -> Element -> Maybe String +getAttr key = fmap attrVal . find ((==) key . attrKey) . elAttribs + setChildren :: [Content] -> Content -> Content setChildren elContent = onContent $ \e -> e {elContent} diff --git a/lib/Text/XML/Light/Serializer.hs b/lib/Text/XML/Light/Serializer.hs index 87ea390..fd92aea 100644 --- a/lib/Text/XML/Light/Serializer.hs +++ b/lib/Text/XML/Light/Serializer.hs @@ -1,12 +1,15 @@ module Text.XML.Light.Serializer ( FromXML(..) , ToXML(..) - , (.=) , decode + , eitherDecode , encode + , (.=) + , expected ) where import Data.List (intercalate) +import Text.Printf (printf) import Text.XML.Light (Attr(..), Content, QName, parseXML, ppContent) import Text.XML.Light.Lexer (XmlSource) @@ -16,14 +19,18 @@ class FromXML a where class ToXML a where toXML :: a -> [Content] -encode :: ToXML a => a -> String -encode = intercalate "\n" . fmap ppContent . toXML - decode :: (XmlSource s, FromXML a) => s -> Maybe a decode = either (\_ -> Nothing) Just . eitherDecode eitherDecode :: (XmlSource s, FromXML a) => s -> Either String a eitherDecode = fromXML . parseXML +encode :: ToXML a => a -> String +encode = intercalate "\n" . fmap ppContent . toXML + (.=) :: Show v => QName -> v -> Attr k .= v = Attr k $ show v + +expected :: String -> [Content] -> Either String a +expected elemType = + Left . printf "Expected %s but got %s" elemType . concat . fmap ppContent -- GitLab