XML: use try/catch with XPath functions
[akkoma] / lib / pleroma / web / xml / xml.ex
1 defmodule Pleroma.Web.XML do
2 require Logger
3
4 def string_from_xpath(_, :error), do: nil
5
6 def string_from_xpath(xpath, doc) do
7 try do
8 {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
9
10 res =
11 res
12 |> to_string
13 |> String.trim()
14
15 if res == "", do: nil, else: res
16 catch
17 e ->
18 Logger.debug("Couldn't find xpath #{xpath} in XML doc")
19 nil
20 end
21 end
22
23 def parse_document(text) do
24 try do
25 {doc, _rest} =
26 text
27 |> :binary.bin_to_list()
28 |> :xmerl_scan.string()
29
30 doc
31 catch
32 :exit, _error ->
33 Logger.debug("Couldn't parse XML: #{inspect(text)}")
34 :error
35 end
36 end
37 end