我正在尝试编写一个 xpickle,它将某种类型的值构造函数序列化为特定属性的 XML 属性值,并将 XML 属性值反序列化回该类型的值构造函数。
我有以下数据:
module Main where
import Text.XML.HXT.Core
newtype Things = Things [Thing]
data Thing = Thing (Maybe Property)
data Property = A | B
someThings :: Things
someThings = Things [ Thing (Just A)
, Thing Nothing
, Thing (Just B)
]
我想将其序列化为:
<things>
<thing property="a" />
<thing />
<thing property="b" />
</things>
这是我正在采取的方法:
instance XmlPickler Things where
xpickle = xpWrap ( \things -> Things things , \(Things things) -> things ) $
xpElem "things" $
xpThings
xpThings :: PU [Thing]
xpThings = xpList xpickle
instance XmlPickler Thing where
xpickle = xpElem "thing" $
xpWrap ( \p -> Thing p , \(Thing p) -> p ) $
xpProperty
xpProperty :: PU (Maybe Property)
xpProperty = xpOption $ xpAttr "property" xpPropertyValue
xpPropertyValue :: PU Property
xpPropertyValue = xpAlt tag ps
where
tag A = 1
tag B = 2
ps = [ xpTextAttr "a"
, xpTextAttr "b"
]
main :: IO ()
main = do
putStrLn $ showPickled [ withIndent yes ] someThings
return ()
在这里,xpProperty
创建或读取一个@property
属性,然后用于xpPropertyValue
计算值。xpPropertyValue
根据值的值构造函数确定值:A
给出"a"
和B
给出"b"
,并且使用xpTextAttr
函数构造值。这里的问题是xpTextAttr
,String -> PU String
我正在尝试在需要PU Property
. 但是我无法找到一种替代方法来生成PU Property
依赖于值的值构造函数的Property
值。