LoginSignup
1
0

More than 1 year has passed since last update.

paiza.ioでelixir その95

Last updated at Posted at 2022-11-24

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

api叩いて、郵便番号から、住所を求めよ。

サンプルコード


:inets.start
:ssl.start


defmodule Main do
	require Record
	Record.defrecord :xmlElement, Record.extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl")
	Record.defrecord :xmlAttribute, Record.extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
	@targets [:state, :city, :address, :state_kana, :city_kana, :address_kana]
	def is_target?(attribute) do
		xmlAttribute(attribute, :name) in @targets
	end
	def parse_address(address_node) do
		attributes = :xmerl_xpath.string('//value', address_node)
			|> Enum.map(&(xmlElement(&1, :attributes)))
			|> Enum.map(fn elems ->
				elems
				|> Enum.filter(&is_target?/1)
			end)
			|> List.flatten
		keys = attributes
			|> Enum.map(&(xmlAttribute(&1, :name)))
		values = attributes
			|> Enum.map(&(to_string xmlAttribute(&1, :value)))
		Enum.into(List.zip([keys, values]), %{})
	end
	def parse_xml(body) do
		{document, _} = body
			|> :binary.bin_to_list
			|> :xmerl_scan.string
		parsed = :xmerl_xpath.string('//ADDRESS_value', document)
			|> Enum.map(&parse_address/1)
	end
    def main() do
        {:ok, {_status, _headers, body}} = :httpc.request('http://zip.cgis.biz/xml/zip.php?zn=9980001')
        body
        body = IO.iodata_to_binary(body)
        parse_xml(body)
        |> IO.inspect
    end
end
Main.main



実行結果

[
  %{
    address: "穂積(その他)",
    address_kana: "ホヅミ(ソノタ)",
    city: "酒田市",
    city_kana: "サカタシ",
    state: "山形県",
    state_kana: "ヤマガタケン"
  }
]

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0