我正在使用Floki解析一些HTML。并收到以下元组:
{"html", [{"lang", "en"}],
[{"head", [],
[{"title", [], ["My App"]},
{"link", [{"rel", "stylesheet"}, {"href", "/css/app.css"}], []}]},
{"body", [],
[{"main", [{"id", "main_container"}, {"role", "main"}], []},
{"script", [{"src", "/js/app.js"}], [""]},
{"iframe",
[{"src", "/phoenix/live_reload/frame"}, {"style", "display: none;"}],
[]}]}]}
是否可以枚举所有元素,以及那些href
或src
添加完整路径的元素?例如,在这种情况下,请将其替换为:http://localhost/css/app.css
和http://localhost/js/app.js
答案 0 :(得分:2)
以下是使用递归函数执行此操作的一种方法。
defmodule HTML do
def use_full_path({el, attrs, children}) do
{el, update_attrs(attrs), Enum.map(children, &use_full_path/1)}
end
def use_full_path(string) do
string
end
defp update_attrs(attrs) do
Enum.map(attrs, fn {key, val} ->
if key in ["href", "src"] do
{key, "http://localhost" <> val}
else
{key, val}
end
end)
end
end
tree = {"html", [{"lang", "en"}],
[{"head", [],
[{"title", [], ["My App"]},
{"link", [{"rel", "stylesheet"}, {"href", "/css/app.css"}], []}]},
{"body", [],
[{"main", [{"id", "main_container"}, {"role", "main"}], []},
{"script", [{"src", "/js/app.js"}], [""]},
{"iframe",
[{"src", "/phoenix/live_reload/frame"}, {"style", "display: none;"}],
[]}]}]}
HTML.use_full_path(tree) |> IO.inspect