我想访问XML文件的数据,例如
<?xml version="1.0"?>
<MY>
<Foo id="1" name="test">
<Argument name="a" />
</Foo>
<Foo id="2" name="test2">
<Argument name="a" />
<Argument name="b" />
</Foo>
<Other id="2" name="someOther"/>
</MY>
我想要例如要读出每个Foo的参数,我该如何用Haskell做到这一点? (我想使用HaXml模块)
我不知道从哪里开始。
最佳答案
我找不到haXml的最新文档和示例。
但是,有一些有关HXT的文档。
我知道这对于您的示例来说可能是一个过大的杀伤力,但是无论如何。
如果要使用tagsoup,则以下答案可能会有所帮助:
xml-tree parser (Haskell) for graph-library
In Haskell how do you extract strings from an XML document?
以下是HXT的示例文档:
http://www.haskell.org/haskellwiki/HXT/Conversion_of_Haskell_data_from/to_XML
http://www.haskell.org/haskellwiki/HXT
http://www.haskell.org/haskellwiki/HXT/Practical
http://en.wikibooks.org/wiki/Haskell/XML
现在,代码使用HXT。
(警告我不确定这是否正确)
我遵循了该教程:
http://www.haskell.org/haskellwiki/HXT/Conversion_of_Haskell_data_from/to_XML
您需要将您的xml文件作为“data.xml”
import Data.Map (Map, fromList, toList)
import Text.XML.HXT.Core
type Foos = Map String [Foo]
data Foo = Foo
{
fooId :: String
, fooName :: String
, arguments :: [Argument]
}
deriving (Show, Eq)
data Argument = Argument
{ argName :: String
}
deriving (Show, Eq)
instance XmlPickler Foo where
xpickle = xpFoo
instance XmlPickler Argument where
xpickle = xpArgument
-- WHY do we need this?? no clue
instance XmlPickler Char where
xpickle = xpPrim
-- this could be wrong
xpFoos :: PU Foos
xpFoos
= xpWrap (fromList
, toList
) $
xpList $
xpElem "MY" $
xpickle
xpFoo :: PU Foo
xpFoo
= xpElem "Foo" $
xpWrap ( uncurry3 Foo
, \ f -> (fooId f
, fooName f
, arguments f
)
) $
xpTriple (xpAttr "id" xpText)
(xpAttr "name" xpText)
(xpList xpickle)
xpArgument :: PU Argument
xpArgument
= xpElem "Argument" $
xpWrap ( \ ((a)) -> Argument a
, \ t -> (argName t)
) $
(xpAttr "name" xpText )
main :: IO ()
main
= do
runX ( xunpickleDocument xpFoos
[ withValidate no
, withTrace 1
, withRemoveWS yes
, withPreserveComment no
] "data.xml"
>>>
arrIO ( \ x -> do {print x ; return x})
)
return ()
结果(您需要将XML示例作为“data.xml”):
-- (1) getXmlContents
-- (1) readDocument: "data.xml" (mime type: "text/xml" ) will be processed
-- (1) readDocument: "data.xml" processed
fromList [("",[Foo {fooId = "1", fooName = "test", arguments = [Argument {argName = "a"}]},
Foo {fooId = "2", fooName = "test2", arguments = [Argument {argName = "a"},
Argument {argName = "b"}]}])]