5

我正在尝试使用 HXT 从 6 行的 XML 输入中提取一些数据。我也想保留 HXT,因为 Curl 集成,而且我还有其他包含数千行的 XML 文件,稍后。

我的 XML 如下所示:

<?xml version = "1.0" encoding = "UTF-8"?>
<find>
    <set_number>228461</set_number>
    <no_records>000000008</no_records>
    <no_entries>000000008</no_entries>
</find>

而且我一直在努力弄清楚如何解析它。不幸的是,HXT 的 Wiki 页面并没有太大帮助(或者我只是忽略了一些东西)。

data FindResult = FindResult {
        resultSetNumber :: String,
        resultNoRecords :: Int,
        resultNoEntries :: Int
    } deriving (Eq, Show)

resultParser :: ArrowXml a => a XmlTree FindResult
resultParser = hasName "find" >>> getChildren >>> proc x -> do
    setNumber <- isElem >>> hasName "set_number" >>> getChildren >>> getText -< x
    noRecords <- isElem >>> hasName "no_records" >>> getChildren >>> getText -< x
    noEntries <- isElem >>> hasName "no_entries" >>> getChildren >>> getText -< x
    returnA -< FindResult setNumber (read noRecords) (read noEntries)

find str = return . head =<< (runX $ readDocument [withValidate no, withCurl []] query >>> resultParser)
    where query = "http://" ++ server ++ "/find?request=" ++ str

我总是得到的是

*** Exception: Prelude.head: empty list

所以,我想,解析一定会出错,因为我检查并正确地从查询中获取了 XML。

4

1 回答 1

6

以下对我有用(仿照此示例):

{-# LANGUAGE Arrows #-}

module Main
       where

import Text.XML.HXT.Core
import System.Environment

data FindResult = FindResult {
        resultSetNumber :: String,
        resultNoRecords :: Int,
        resultNoEntries :: Int
    } deriving (Eq, Show)

resultParser :: ArrowXml a => a XmlTree FindResult
resultParser =
  deep (isElem >>> hasName "find") >>> proc x -> do
    setNumber <- getText <<< getChildren <<< deep (hasName "set_number") -< x
    noRecords <- getText <<< getChildren <<< deep (hasName "no_records") -< x
    noEntries <- getText <<< getChildren <<< deep (hasName "no_entries") -< x
    returnA -< FindResult setNumber (read noRecords) (read noEntries)

main :: IO ()
main = do [src] <- getArgs
          res <- runX $ ( readDocument [withValidate no] src >>> resultParser)
          print . head $ res

测试:

$ dist/build/test/test INPUT
FindResult {resultSetNumber = "228461", resultNoRecords = 8, resultNoEntries = 8}
于 2011-07-01T12:37:15.917 回答