xml.ex 720 Bytes
Newer Older
lain's avatar
lain committed
1
defmodule Pleroma.Web.XML do
lain's avatar
lain committed
2
3
  require Logger

Thog's avatar
Thog committed
4
  def string_from_xpath(_, :error), do: nil
lain's avatar
lain committed
5

lain's avatar
lain committed
6
  def string_from_xpath(xpath, doc) do
7
8
    try do
      {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
lain's avatar
lain committed
9

10
11
12
13
      res =
        res
        |> to_string
        |> String.trim()
lain's avatar
lain committed
14

15
16
17
18
19
20
      if res == "", do: nil, else: res
    catch
      e ->
        Logger.debug("Couldn't find xpath #{xpath} in XML doc")
        nil
    end
lain's avatar
lain committed
21
22
23
  end

  def parse_document(text) do
lain's avatar
lain committed
24
    try do
lain's avatar
lain committed
25
26
27
28
      {doc, _rest} =
        text
        |> :binary.bin_to_list()
        |> :xmerl_scan.string()
lain's avatar
lain committed
29

lain's avatar
lain committed
30
31
      doc
    catch
Thog's avatar
Thog committed
32
      :exit, _error ->
feld's avatar
feld committed
33
        Logger.debug("Couldn't parse XML: #{inspect(text)}")
lain's avatar
lain committed
34
35
        :error
    end
lain's avatar
lain committed
36
37
  end
end