如何在Haskell中重新实现这个Python XML解析函数?

Sno*_*ual 4 python xml haskell

我最近编写了以下Python函数,该函数将使用Google Picasa contacts.xml文件并输出带有ID和名称的字典.

def read_contacts_file(fn):
    import xml.etree.ElementTree
    x = xml.etree.ElementTree.ElementTree(file=fn)
    q = [(u.attrib["id"], u.attrib["name"]) for u in x.iter("contact")]
    return dict(q)
Run Code Online (Sandbox Code Playgroud)

这个函数的作用是返回一个字典(哈希表,映射),其中ID是键,Name是值.

该文件本身具有以下形式:

<contacts>
 <contact id="f5fdaaee2e80fa01" name="Person A" display="A"/>
 <contact id="8d5256298fd43877" name="Person B" display="B"/>
</contacts>
Run Code Online (Sandbox Code Playgroud)

我在Haskell中实现这个的最简单方法是什么?


只是想让你知道,在大家的帮助下,我已经设法提出以下对我有意义的事情.谢谢.

parseContactsData = M.fromList . runLA (xread >>> f) 
    where f = 
        getChildren 
        >>> hasName "contact" 
        >>> getAttrValue "id" &&& getAttrValue "name"
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 7

这是一个用tagsoup做同样事情的最小例子:

import Text.HTML.TagSoup

assocLookup k dict = [v | (k', v) <- dict, k == k']
readContactsFile fn = fmap parse (readFile fn)

parse contents = do
    TagOpen "contact" attrs <- parseTags contents
    id <- assocLookup "id" attrs
    name <- assocLookup "name" attrs
    return (id, name)
Run Code Online (Sandbox Code Playgroud)


Ant*_*ony 6

这是用HXT做的一个例子

import Text.XML.HXT.Core
import Data.Map

idAssocs = hasName "contact" >>> getAttrValue "id" &&& getAttrValue "name"
dict = fromList `fmap` runX (readDocument [] "contacts.xml" >>> deep idAssocs)
Run Code Online (Sandbox Code Playgroud)