我在 Andrew Birkett 的博客Applicative arrows for XML &&& return to pure上读到,我们可以混合使用箭头和应用函子。
我自己尝试过,但我没有我所期望的。我想要这个结果:
[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)