I am using HXT to parse a simple XML file and need to replace missing attributes of a tag with default value. But for some reason orElse
does not work as expected.
Below is XML file:
<!-- window_home.xml -->
<elements>
<Window libraryItemName="panel_tabs" name="panel_tabs" selected="true">
<matrix>
<Matrix ty="-11.8" />
</matrix>
</Window>
<Window libraryItemName="home_powerup_menu" name="home_powerup_menu" selected="true">
<matrix>
<Matrix tx="12.4" />
</matrix>
</Window>
<Window libraryItemName="panel_name" name="panel_name" selected="true">
<!-- data here -->
</Window>
</elements>
Tag in question is Matrix
.
Below is my code:
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
import Text.XML.HXT.Core
parseXML = readDocument [ withValidate no
, withRemoveWS yes -- throw away formating WS
]
atTag tag = deep (isElem >>> hasName tag)
data XflMatrix = XflMatrix { a, b, c, d, tx, ty :: Float } deriving (Show)
initXflMatrix = XflMatrix { a = 1.0, d = 1.0, b = 0.0, c = 0.0, tx = 0.0, ty = 0.0 }
data UiWindow = UiWindow {
wndName :: String,
wndNameLib :: String,
wndMatrix :: XflMatrix,
wndChildren :: [UiWindow]
} deriving (Show)
initUiWindow = UiWindow {
wndName = "empty",
wndNameLib = "",
wndMatrix = initXflMatrix,
wndChildren = []
}
parseDoc docName = runX $ parseXML fileName >>> getWindow
where
fileName = docName ++ ".xml"
getMatrixFromTag = atTag "Matrix" >>> proc x -> do
tx <- getFloatAttrib "tx" -< x
ty <- getFloatAttrib "ty" -< x
returnA -< initXflMatrix { tx = read tx :: Float, ty = read ty :: Float }
where
--getFloatAttrib attribName = getAttrValue attribName
getFloatAttrib attribName = getAttrValue attribName `orElse` constA "0.0"
getWindow = atTag "Window" >>> proc x -> do
libraryItemName <- getAttrValue "libraryItemName" -< x
name <- getAttrValue "name" -< x
m <- getMatrixFromTag -< x
children <- arrIO parseDoc -< libraryItemName
returnA -< initUiWindow { wndName = name, wndNameLib = libraryItemName, wndChildren = children, wndMatrix = m}
documentName = "DOMDocument.xml"
parseRoot = parseXML documentName
--runX (parseRoot >>> getWindow )
It looks like the line
getFloatAttrib attribName = getAttrValue attribName `orElse` constA "0.0"
Does not return "0.0"
.
Am I doing something wrong?
Ok, that was stupid. I should have checked the types:
λ: :t getAttrValue
getAttrValue :: ArrowXml a => String -> a XmlTree String
λ: :t hasAttr
hasAttr :: ArrowXml a => String -> a XmlTree XmlTree
Now, after changing the line in question to:
getFloatAttrib attribName = (hasAttr attribName >>> getAttrValue attribName) `orElse` constA "0.0"
Everything is fine.