首页 > 解决方案 > 在 Arrow proc 上下文中提取多个元素

问题描述

我想解析以下示例 XML 文件,而不使用 pickler 模块。

<?xml version="1.0" encoding="utf-8" ?>
<Groups> 
    <Name>ABC</Name>
    <GroupA>
        <Name>Foo</Name>
        <Sum>100</Sum>
    </GroupA>
    <GroupB>
        <Name>Bar</Name>
        <Sum>0</Sum>
    </GroupB>
</Groups>

我最终得到了这个:

{-# language Arrows #-}

import Text.XML.HXT.Core

data Groups = Groups GroupA GroupB deriving Show
data GroupA = GroupA String String deriving Show
data GroupB = GroupB String String deriving Show


readGroup :: LA XmlTree Groups
readGroup = deep (isElem >>> hasName "Groups") >>> getChildren >>>
  proc root -> do
    a <- readGroupA -< root
    b <- readGroupB -< root
    returnA -< Groups a b

readGroupA :: LA XmlTree GroupA
readGroupA = isElem >>> hasName "GroupA" >>> getChildren >>>
  proc root -> do
    n <- isElem >>> hasName "Name" /> getText -< root
    s <- isElem >>> hasName "Sum"  /> getText -< root
    returnA -< GroupA n s

readGroupB :: LA XmlTree GroupB
readGroupB = isElem >>> hasName "GroupB" >>> getChildren >>>
  proc root -> do
    n <- isElem >>> hasName "Name" /> getText -< root
    s <- isElem >>> hasName "Sum"  /> getText -< root
    returnA -< GroupB n s

不幸的是,这不起作用。proc如果我尝试在上下文中仅提取单个元素,它会起作用。但是尝试提取多个元素总是会失败\返回空列表。我可能对作文有误解>>>

我运行这个例子runLa (xreadDoc >>> readGroups)

标签: xmlhaskellhxt

解决方案


尝试这个:

readGroup :: LA XmlTree Groups
readGroup = deep (isElem >>> hasName "Groups") >>>
  proc root -> do
    a <- getChildren >>> readGroupA -< root
    b <- getChildren >>> readGroupB -< root
    returnA -< Groups a b

readGroupA :: LA XmlTree GroupA
readGroupA = isElem >>> hasName "GroupA" >>>
  proc root -> do
    n <- getChildren >>> isElem >>> hasName "Name" /> getText -< root
    s <- getChildren >>> isElem >>> hasName "Sum"  /> getText -< root
    returnA -< GroupA n s

readGroupB :: LA XmlTree GroupB
readGroupB = isElem >>> hasName "GroupB" >>>
  proc root -> do
    n <- getChildren >>> isElem >>> hasName "Name" /> getText -< root
    s <- getChildren >>> isElem >>> hasName "Sum"  /> getText -< root
    returnA -< GroupB n s

当调用在-blockgetChildren之外时,您甚至在进入. 在 内部,您检查(例如)该孩子是否有 namename 。不出所料,您找不到任何符合这些矛盾要求的孩子。doprocprocName Sum

通过getChildren向内移动,您允许遍历(例如)n和的不同子级s


推荐阅读