我正在编写一个用于处理图形的库。
主要任务 - 解析 xml-tree。
这棵树看起来像
<graph nodes=4 arcs=5>
<node id=1 />
<node id=2 />
<node id=3 />
<node id=4 />
<arc from=1 to=2 />
<arc from=1 to=3 />
<arc from=1 to=4 />
<arc from=2 to=4 />
<arc from=3 to=4 />
</graph>
存储结构:
type Id = Int
data Node = Node Id deriving (Show)
data Arc = Arc Id Id deriving (Show)
data Graph = Graph { nodes :: [Node],
arcs :: [Arc]}
如何将xml文件中的数据写入这个结构中?
我无法为这种类型的 xml 树编写解析器(HXT 库)
您需要使用 XML 库吗?这'标签汤' http://hackage.haskell.org/package/tagsoup库对于 not-really-xml 可能同样有效,如下所示:
import Text.HTML.TagSoup
import Data.Maybe
main = do
s <- readFile "A.dat"
-- get a list of nodes and arcs
let g' = catMaybes
[ case n of
TagOpen "node" [(_,n)] -> Just (Left $ Node (read n))
TagOpen "arc" [(_,n), (_,m)] -> Just (Right $ Arc (read n) (read m))
_ -> Nothing
| n <- parseTags s ]
-- collapse them into a graph
let g = foldr (\n g -> case n of
Left n -> g { nodes = n : nodes g }
Right a -> g { arcs = a : arcs g }
) (Graph [] []) g'
print g
运行这个:
> main
Graph {nodes = [Node 1,Node 2,Node 3,Node 4], arcs = [Arc 1 2,Arc 1 3,Arc 1 4,Arc 2 4,Arc 3 4]}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)