我正在尝试阅读XML Feed表单" http://www.rssboard.org/files/sample-rss-2.xml"
我能够在Enum(Enum.each(XmlNode.all)中获得一个列(标题),但是如何以下面显示的表格格式显示另一个类似描述的列?
Fetcher.ex:
{:ok, %HTTPoison.Response{body: body}} = HTTPoison.get("http://www.rssboard.org/files/sample-rss-2.xml")
doc = XmlNode.from_string(body)
# This prints only title and not description along with it.
# I want to get title and description in tabular format
Enum.each(XmlNode.all(doc, "//title"), fn(node) ->
IO.puts "#{XmlNode.node_name(node)} #{XmlNode.attr(node,"Title:")} end)
XMLNode.ex:
defmodule XmlNode do
require Record
Record.defrecord :xmlAttribute, Record.extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
def from_string(xml_string, options \\ [quiet: true]) do
{doc, []} =
xml_string
|> :binary.bin_to_list
|> :xmerl_scan.string(options)
doc
end
def all(node, path) do
for child_element <- xpath(node, path) do
child_element
end
end
def first(node, path), do: node |> xpath(path) |> take_one
defp take_one([head | _]), do: head
defp take_one(_), do: nil
def node_name(nil), do: nil
def node_name(node), do: elem(node, 1)
def attr(node, name), do: node |> xpath('./@#{name}') |> extract_attr
defp extract_attr([xmlAttribute(value: value)]), do: List.to_string(value)
defp extract_attr(_), do: nil
def text(node), do: node |> xpath('./text()') |> extract_text
defp extract_text([xmlText(value: value)]), do: List.to_string(value)
defp extract_text(_x), do: nil
defp xpath(nil, _), do: []
defp xpath(node, path) do
:xmerl_xpath.string(to_char_list(path), node)
end
end
预期产出:
Title | Description
-------------------------------
title 1 | description 1
title 2 | description 2