Skip to content

Instantly share code, notes, and snippets.

@mazz
Forked from spint/elixir_xml.exs
Created July 4, 2017 02:51
Show Gist options
  • Save mazz/38b5baa2bbc55132b98524485370aecf to your computer and use it in GitHub Desktop.
Save mazz/38b5baa2bbc55132b98524485370aecf to your computer and use it in GitHub Desktop.
Elixir XML processing (to JSON) with SweetXML
# mix.exs file dependencies:
# defp deps do
# [
# {:sweet_xml, "~> 0.4.0"},
# {:json, "~> 0.3.0"}
# ]
# end
defmodule ElixirXml do
import SweetXml
def count_items(file) do
File.stream!(file, [:read]) |> xpath(~x"//PatBase/Family/Patent"l) |> length
end
def elements(file) do
# s-option forces to return strings instead of char lists
File.stream!(file, [:read]) |> xpath(~x"//PatBase/Family/Patent"l, title: ~x"./Title/btitle/text()"s, pub_date: ~x"./PublicationDate/text()"s, pub_number: ~x"./PublicationNumber/text()"s )
end
def parse(file) do
elements(file) |> to_json
end
defp to_json(attr_array) do
JSON.encode(attr_array)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment