如何使用Haskell访问某些XML数据(使用HaXml)?

前端之家收集整理的这篇文章主要介绍了如何使用Haskell访问某些XML数据(使用HaXml)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望能够访问 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>

我想要,例如用它的Arguments读出每个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"}]}])]
原文链接:https://www.f2er.com/xml/292517.html

猜你在找的XML相关文章