我在Andrew Birkett的博客上读到应用箭头用于XML和返回纯函数,我们可以混合使用箭头和应用函子。
我自己尝试了一下,但结果并不如我所愿。 我希望得到这个结果:
[Scenario {scenario = "11111", origin = "333", alarm = "Sonde1"},
Scenario {scenario = "22222", origin = "444", alarm = "Sonde2"}]
但我得到了以下结果:
[Scenario {scenario = "11111", origin = "333", alarm = "Sonde1"},
Scenario {scenario = "11111", origin = "333", alarm = "Sonde2"},
Scenario {scenario = "11111", origin = "444", alarm = "Sonde1"},
Scenario {scenario = "11111", origin = "444", alarm = "Sonde2"},
Scenario {scenario = "22222", origin = "333", alarm = "Sonde1"},
Scenario {scenario = "22222", origin = "333", alarm = "Sonde2"},
Scenario {scenario = "22222", origin = "444", alarm = "Sonde1"},
Scenario {scenario = "22222", origin = "444", alarm = "Sonde2"}]
我认为我的代码有问题,但我不知道在哪里查找。
以下是我的代码,如果有人能提供帮助,请告诉我。
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
import Text.XML.HXT.Core
import Control.Applicative
import Text.XML.HXT.Arrow.ReadDocument
import Data.Maybe
import Text.XML.HXT.XPath.Arrows
import Text.Printf
data Scenario = Scenario
{ scenario, origin, alarm :: String
}
deriving (Show, Eq)
xml= "<DATAS LANG='en'>\
\ <SCENARIO ID='11111'>\
\ <ORIGIN ID='333'>\
\ <SCENARIO_S ERR='0'></SCENARIO_S>\
\ <SCENARIO_S ERR='2'></SCENARIO_S>\
\ <ALARM_M NAME='Sonde1'></ALARM_M>\
\ </ORIGIN>\
\ </SCENARIO>\
\ <SCENARIO ID='22222'>\
\ <ORIGIN ID='444'>\
\ <SCENARIO_S ERR='10'></SCENARIO_S>\
\ <SCENARIO_S ERR='12'></SCENARIO_S>\
\ <ALARM_M NAME='Sonde2'></ALARM_M>\
\ </ORIGIN>\
\ </SCENARIO>\
\</DATAS>"
parseXML string = readString [ withValidate no
, withRemoveWS yes -- throw away formating WS
] string
parseVal tag name = WrapArrow $ getXPathTrees (printf "/DATAS/%s" tag) >>> getAttrValue name
parseDatas = unwrapArrow $ Scenario <$> parseVal "SCENARIO" "ID"
<*> parseVal "SCENARIO/ORIGIN" "ID"
<*> parseVal "SCENARIO/ORIGIN/ALARM_M" "NAME"
testarr1= runX (parseXML xml >>> parseDatas)