scrape v3.1.0 Scrape.Tools.Tree

Utility module for interacting with nested Map structures, here called "tree".

Link to this section Summary

Functions

Attempts to get a nested value from the tree using a string selector syntax.

Applies find/2 to all given selectors and combines the result.

Attempts all queries until one returns a non-nil result or nil.

Transform a given xml string into a tree.

Link to this section Functions

Link to this function

find(tree, selector)
find(map(), String.t()) :: any()

Attempts to get a nested value from the tree using a string selector syntax.

Returns nil if nothing matches the selector or all matching results.

Examples

iex> Tree.find(%{"a" => %{"b" => "c"}}, "a")
%{"b" => "c"}

iex> Tree.find(%{"a" => %{"b" => "c"}}, "a.b")
"c"

iex> Tree.find(%{"a" => %{"b" => "c"}}, "unknown")
nil

iex> Tree.find(%{"a" => [%{"b" => "c"}]}, "a.b")
["c"]

iex> Tree.find(%{"a" => [%{"b" => [%{"c" => "d"}]}]}, "a.b.c")
["d"]

iex> Tree.find(%{"a" => [%{"b" => "c"}, %{"b" => "c"}]}, "a.b")
["c", "c"]

iex> Tree.find(%{"a" => [%{"b" => [%{"c" => "d"}]}]}, "a.*.c")
["d"]

iex> Tree.find(%{"hello" => "world"}, "~ell")
["world"]
Link to this function

find_all(tree, selectors)
find_all(map(), [String.t()]) :: [any()]

Applies find/2 to all given selectors and combines the result.

Examples

iex> Tree.find_all(%{"a" => "b", "c" => "d"}, ["a", "c"])
["b", "d"]

iex> Tree.find_all(%{"a" => "b", "c" => "d"}, ["a", "z"])
["b"]

iex> Tree.find_all(%{"a" => "b", "c" => "d"}, ["x", "y"])
[]
Link to this function

first(tree, list)
first(map(), [String.t()]) :: nil | any()

Attempts all queries until one returns a non-nil result or nil.

Examples

iex> Tree.first(%{"hello" => "world"}, ["unknown"])
nil

iex> Tree.first(%{"hello" => "world"}, ["unknown", "hello"])
"world"
Link to this function

from_xml_string(xml)
from_xml_string(String.t()) :: map()

Transform a given xml string into a tree.

The string must be utf-8 encoded. It will be sanitized via Floki and the xml declaration header will be stripped.

Examples

iex> Tree.from_xml_string("<feed><item>abc</item></feed>")
%{"feed" => %{"item" => "abc"}}