Hxt和解析可选元素

时间:2017-07-20 23:12:36

标签: haskell hxt

我试着用以下xml片段中的HXT解析可选元素:

<ns9:accountBankingInfo>
  <key>
    <accountId>10</accountId>
    <bankingId>01</bankingId>
  </key>
  <bankingInfo>
    <description>Bigbank Co.</description>
    <eft>
        <bankCode>222</bankCode>
        <transit>111</transit>
        <accountNumber>3333333</accountNumber>
    </eft>
   </bankingInfo>
   <defaultType>ACCOUNT</defaultType> <!-- optional -->
</ns9:accountBankingInfo>

我使用Maybe来表示defaultType元素:

data BankingInfo = BankingInfo { bankingID   :: String
                               , bankingDesc :: String
                               , bankCode    :: String  
                               , bankTransit :: String  
                               , bankAccount :: String
                               , defaultType :: Maybe String  
                               } deriving (Show, Eq)

我正在解析accountBankingInfo元素,如下所示:

bankParser :: ArrowXml a => a XmlTree BankingInfo
bankParser = deep (isElem >>> hasLocalPart "accountBankingInfo") >>> proc x -> do
                   i <- getText <<< getChildren <<< deep (hasName "bankingId") -< x
                   d <- getText <<< getChildren <<< deep (hasName "description") -< x
                   b <- getText <<< getChildren <<< deep (hasName "bankCode") -< x
                   t <- getText <<< getChildren <<< deep (hasName "transit") -< x
                   a <- getText <<< getChildren <<< deep (hasName "accountNumber") -< x
                   g <- nc "defaultType" -< x

                   returnA -< BankingInfo i d b t a g

nc name = ifA (deep (hasName name)) (getChildren >>> getText >>> arr Just) (arr (const Nothing))

它编译,但是当我解析文件时,我没有得到任何BankingInfo返回。如果我更改BankingInfo类型以删除defaultType并且不担心解析该元素,那么一切都会成功。

是否有一种简单的方法来处理XML中的可选元素并将其转换为Maybe x?

1 个答案:

答案 0 :(得分:0)

我刚刚发现了withDefault函数,并且能够让它像这样工作:

bankParser :: ArrowXml a => a XmlTree BankingInfo
bankParser = deep (isElem >>> hasLocalPart "accountBankingInfo") >>> proc x -> do
                   i <- getText <<< getChildren <<< deep (hasName "bankingId") -< x
                   d <- getText <<< getChildren <<< deep (hasName "description") -< x
                   b <- getText <<< getChildren <<< deep (hasName "bankCode") -< x
                   t <- getText <<< getChildren <<< deep (hasName "transit") -< x
                   a <- getText <<< getChildren <<< deep (hasName "accountNumber") -< x
                   g <- withDefault (arr Just <<< getText <<< getChildren <<< deep (hasName "defaultType")) Nothing -< x
                   returnA -< BankingInfo i d b t a g