SpecialSnowflake
SpecialSnowflake

Reputation: 995

Returning specific xml tag with erlang

get_currency() ->       
URL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22GBPEUR%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
{Result, Info} = httpc:request(URL),
case Result of
    error -> 
        {Result, Info};
    ok ->
        {{_Protocol, Code, _CodeStr}, _Attrs, WebData} = Info,
        WebData
    end.

extract_text(Content) ->
Item = hd(Content),
case element(1, Item) of
    xmlText -> Item#xmlText.value;
    _ -> ""
end.



analyze_info(WebData) ->        
ToFind = [rate],
Parsed = element(1, xmerl_scan:string(WebData)),
Children = Parsed#xmlElement.content,
ElementList = [{El#xmlElement.name, extract_text(El#xmlElement.content)} || El <- Children, element(1, El) == xmlElement],
lists:map(fun(Item) -> lists:keyfind(Item, 1, ElementList) end, ToFind).

the above is the code im using to try to extract the contents of the tag from the url http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22GBPEUR%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys.

here is what i do in the shell.

inets:start().
XML = scrapetest:get_currency().
scrapetest:analyze_info(XML).

and the return i get is simply "false". Im not sure what im doing wrong.

Upvotes: 1

Views: 558

Answers (1)

cybergrind
cybergrind

Reputation: 792

Just add some logs to your code.

Eg. adding io:format("~p~n", [ElementList]), - will show you that ElementList contains only result tag, and you should go one level deeper in your list comprehension to get tag named rate

This is common advice.

In your case, seems that better decision is recursive find function (if you want to write some code)

or use some batteries, like xmerl_xpath

Just example for another analyze_info :

analyze_info(WebData) -> 
  Parsed = element(1, xmerl_scan:string(WebData)),
  xmerl_xpath:string("//Rate/text()", Parsed).

This will return:

[{xmlText,[{'Rate',2},{rate,1},{results,1},{query,1}],
      1,[],"1.1813",text}]

Upvotes: 2

Related Questions