View Category
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<shopping>
<item name=
"bread" quantity="3" price="2.50"/>
<item name=
"milk" quantity="2" price="3.50"/>
</shopping>
Print out the total cost of the items, e.g. $14.50
haskell
File Edit Options Buffers Tools Haskell Help
import Text.ParserCombinators.Parsec
import Control.Monad
import System ( getArgs )
data Item = Item { name :: String,
quantity :: Int,
price :: Int }
deriving Show
type Basket = [Item]
item :: Parser Item
item = do string "<item name=\""
name <- manyTill letter (char '\"')
string " quantity=\""
quantity <- liftM read $ many digit
string "\" price=\""
dollars <- liftM read $ many digit
cents <- option 0 (char '.' >> (liftM read $ many digit))
string "\"/>"
return $ Item name quantity (100 * dollars + cents)
basket :: Parser Basket
basket = do string "<shopping>"
items <- manyTill item (try $ string "</shopping>")
return items
parseBasket :: String -> Basket
parseBasket input = case parse basket "Shopping Basket" input of
Left _ -> []
Right val -> val
main = do args <- getArgs
putStrLn $ show . (/100) . fromIntegral . sum . map (\(Item _ q p) -> q * p) . parseBasket $ head args
import Text.ParserCombinators.Parsec
import Control.Monad
import System ( getArgs )
data Item = Item { name :: String,
quantity :: Int,
price :: Int }
deriving Show
type Basket = [Item]
item :: Parser Item
item = do string "<item name=\""
name <- manyTill letter (char '\"')
string " quantity=\""
quantity <- liftM read $ many digit
string "\" price=\""
dollars <- liftM read $ many digit
cents <- option 0 (char '.' >> (liftM read $ many digit))
string "\"/>"
return $ Item name quantity (100 * dollars + cents)
basket :: Parser Basket
basket = do string "<shopping>"
items <- manyTill item (try $ string "</shopping>")
return items
parseBasket :: String -> Basket
parseBasket input = case parse basket "Shopping Basket" input of
Left _ -> []
Right val -> val
main = do args <- getArgs
putStrLn $ show . (/100) . fromIntegral . sum . map (\(Item _ q p) -> q * p) . parseBasket $ head args
import Text.XML.HXT.Core
import Text.Printf
main :: IO ()
main = do
prices <- runX (process "basket.xml")
printf "$%.2f\n" $ sum prices
process :: FilePath -> IOSArrow XmlTree Double
process filename =
readDocument [withValidate no] filename >>>
getChildren >>>
isElem >>> hasName "shopping" >>>
getChildren >>>
isElem >>> hasName "item" >>>
getQuantity &&& getPrice >>>
arr (uncurry (*))
getQuantity :: IOSArrow XmlTree Double
getQuantity =
getAttrl >>> hasName "quantity" >>> getChildren >>>
getText >>> arr read
getPrice :: IOSArrow XmlTree Double
getPrice =
getAttrl >>> hasName "price" >>> getChildren >>>
getText >>> arr read
import Text.Printf
main :: IO ()
main = do
prices <- runX (process "basket.xml")
printf "$%.2f\n" $ sum prices
process :: FilePath -> IOSArrow XmlTree Double
process filename =
readDocument [withValidate no] filename >>>
getChildren >>>
isElem >>> hasName "shopping" >>>
getChildren >>>
isElem >>> hasName "item" >>>
getQuantity &&& getPrice >>>
arr (uncurry (*))
getQuantity :: IOSArrow XmlTree Double
getQuantity =
getAttrl >>> hasName "quantity" >>> getChildren >>>
getText >>> arr read
getPrice :: IOSArrow XmlTree Double
getPrice =
getAttrl >>> hasName "price" >>> getChildren >>>
getText >>> arr read
fantom
sum := 0.0
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")
root := XParser(File(`shop.xml`).in).parseDoc.root
if (root.name == "shopping")
{
root.elems.each
{
if (it.name == "item")
{
quantity := Int.fromStr(it.get("quantity"))
price := Decimal.fromStr(it.get("price"))
sum += quantity * price;
}
}
}
echo("\$$sum")
erlang
-include_lib("xmerl/include/xmerl.hrl").
-export([get_total/1]).
get_total(ShoppingList) ->
{XmlElt, _} = xmerl_scan:string(ShoppingList),
Items = xmerl_xpath:string("/shopping/item", XmlElt),
Total = lists:foldl(fun(Item, Tot) ->
[#xmlAttribute{value = PriceString}] = xmerl_xpath:string("/item/@price", Item),
{Price, _} = string:to_float(PriceString),
[#xmlAttribute{value = QuantityString}] = xmerl_xpath:string("/item/@quantity", Item),
{Quantity, _} = string:to_integer(QuantityString),
Tot + Price*Quantity
end,
0, Items),
io:format("$~.2f~n", [Total]).
-export([get_total/1]).
get_total(ShoppingList) ->
{XmlElt, _} = xmerl_scan:string(ShoppingList),
Items = xmerl_xpath:string("/shopping/item", XmlElt),
Total = lists:foldl(fun(Item, Tot) ->
[#xmlAttribute{value = PriceString}] = xmerl_xpath:string("/item/@price", Item),
{Price, _} = string:to_float(PriceString),
[#xmlAttribute{value = QuantityString}] = xmerl_xpath:string("/item/@quantity", Item),
{Quantity, _} = string:to_integer(QuantityString),
Tot + Price*Quantity
end,
0, Items),
io:format("$~.2f~n", [Total]).
create some XML programmatically
Given the following CSV:
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
<item name=
</shopping>
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
"bread" quantity="3" price="2.50" />
<item name=
"milk" quantity="2" price="3.50" />
</shopping>
fantom
sum := 0.0
rows := CsvInStream(File(`shop.csv`).in).readAllRows
doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}
os := File(`shop.xml`).out
doc.write(os)
os.close
rows := CsvInStream(File(`shop.csv`).in).readAllRows
doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}
os := File(`shop.xml`).out
doc.write(os)
os.close
erlang
to_xml(ShoppingList) ->
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
