Merge remote-tracking branch 'pleroma/develop' into cycles-pipeline
[akkoma] / lib / pleroma / web / xml.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.XML do
6 require Logger
7
8 def string_from_xpath(_, :error), do: nil
9
10 def string_from_xpath(xpath, doc) do
11 try do
12 {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
13
14 res =
15 res
16 |> to_string
17 |> String.trim()
18
19 if res == "", do: nil, else: res
20 catch
21 _e ->
22 Logger.debug("Couldn't find xpath #{xpath} in XML doc")
23 nil
24 end
25 end
26
27 def parse_document(text) do
28 try do
29 {doc, _rest} =
30 text
31 |> :binary.bin_to_list()
32 |> :xmerl_scan.string(quiet: true)
33
34 {:ok, doc}
35 rescue
36 _e ->
37 Logger.debug("Couldn't parse XML: #{inspect(text)}")
38 :error
39 catch
40 :exit, _error ->
41 Logger.debug("Couldn't parse XML: #{inspect(text)}")
42 :error
43 end
44 end
45 end