我正在尝试运行以下代码,它在->
{- Make sure you have the hxt, url and http packages:
cabal install hxt
cabal install url
cabal install http
cabal install hxt-curl -}
import Text.XML.HXT.Core
import Network.HTTP
import Network.URI
weatherDataURL = "http://www.weather.gov/xml/current_obs/KAGC.xml"
retrieveWeatherData = do
case parseURI weatherDataURL of
Nothing -> ioError . userError $ "Invalid URL"
Just uri -> get uri
{- | Download a URL. (Left errorMessage) if an error, (Right doc) if success. -}
get uri = do
eresp <- simpleHTTP (Request uri GET [] "")
case eresp of
Left _ -> ioError . userError $ "Failed to get " ++ show uri
Right res -> return $ rspBody res
{-readString :: Attributes -> String -> IOStateArrow s b XmlTreeSource read a document
that is stored in a normal Haskell String the same function as readDocument, but the
parameter forms the input. All options available for readDocument are applicable for
readString. -}
parseXML doc = readString [ withValidate no --turn off the validation step.
, withRemoveWS yes ---- throw away formatting WS
] doc
data Weather = Weather
{ location, observationTime,
summary, windDirection :: String,
temperature, humidity,
dewpoint,
pressure, windSpeed,
visibility :: Float }
deriving (Eq, Show)
atTag tag = deep (isElem >>> hasName tag) -- Selecting all "top level" tag in XML document
text = getChildren >>> getText
textAtTag tag = atTag tag >>> text
getWeather = atTag "current_observation" >>>
proc x -> do -- proc (arrow abstraction) except that it constructs an arrow instead of a function.
loc <- textAtTag "location" -< x -- reserved symbol used for building commands from an expression of arrow type and an expression to be fed as input to that arrow
obsTime <- textAtTag "observation_time" -< x
summ <- textAtTag "weather" -< x
windDir <- textAtTag "wind_dir" -< x
temp <- textAtTag "temp_c" -< x
humi <- textAtTag "relative_humidity" -< x
wind <- textAtTag "wind_mph" -< x
pres <- textAtTag "pressure_mb" -< x
dew <- textAtTag "dewpoint_c" -< x
vis <- textAtTag "visibility_mi" -< x
returnA -< Weather
{ location = loc,
observationTime = obsTime,
summary = summ,
windDirection = windDir,
temperature = read temp,
humidity = read humi,
windSpeed = read wind * 1.61,
pressure = read pres,
dewpoint = read dew,
visibility = read vis * 1.61 }
-- GHCi test:
-- Main> retrieveWeatherData >>= \ doc -> runX (parseXML doc >>> getWeather)
main = do
doc <- retrieveWeatherData
xml <- return $ parseXML doc
result <- runX (xml >>> getWeather)
case result of
[] -> putStrLn "Unable to parse weather data."
w:_ -> print w
答案 0 :(得分:7)
我猜 1 你的解析错误就在这一行:
proc x -> do
如果是这样,那意味着您还没有告诉您的友好邻居Haskell编译器您希望它支持箭头语法。你可以把它放在文件的顶部:
{-# LANGUAGE Arrows #-}
1 但将来请告诉我们,我们不能 猜测。