2011-07-01 5 views
5

HXTを使用してXML入力から6行のデータを抽出しようとしています。私は、Curlの統合と、後で数千行のXMLファイルを持っているので、HXTも保持したいと思っています。単純な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 

ので、私は推測し、解析がクエリからXMLを取得し、正しく私がチェックするので、恐ろしく間違って行くとしなければならない

*** Exception: Prelude.head: empty list 

です。

答えて

6

this exampleをモデルにした)私のために、次の作品:

{-# 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} 
+0

多くの感謝! – Lanbo

関連する問題