如何检查Elixir中的XML是否格式正确

时间:2014-11-04 20:34:51

标签: xml elixir well-formed

我收到的XML文件可能格式不正确,在这种情况下我需要忽略它们。

我正在使用包装xmerl的SweetXml。

我有一个格式错误的XML,它在两个属性之间没有空格。

没有is_well_formed函数 - 一个带有简单布尔响应的函数会很棒。

Xmerl尝试解析文件,不喜欢它,因此发送一个退出。

我还没有了解过主管,但这对我来说就是一个例子。

是否有新手或简单的处理退出信号的方式?

defmodule XmlIsWellFormed.WellFormed do
  def is_well_formed(xml) do
    import SweetXml
    xml_string = to_string xml
    result = xml_string |> parse # parse sends exit.

    # FYI - SweetXml.parse :
    # def parse(doc) do
    #     {parsed_doc, _} = :xmerl_scan.string(doc)
    #     parsed_doc
    # end

    # Note:     inspecting result is no use because xmerl sends an exit with:
    #           "whitespace_required_between_attributes"

    # Something like this would be handy:
    # try do
    #     result = :xmerl_scan.string(xml)
    # rescue
    #     :exit, _ -> nil
    # end
  end
end

rubbish_xml = '<rubbishml><html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml"></rubbishml>'
XmlIsWellFormed.WellFormed.is_well_formed rubbish_xml

1 个答案:

答案 0 :(得分:4)

您使用try/rescue,它只拦截异常。另一方面,退出可以使用try/catch construct

截取
def is_well_formed(xml) do
  try do
    xml |> to_string |> parse
    true
  catch
    :exit, _ -> false
  end
end

IEX会将退出消息打印到控制台,但程序将继续执行:

iex> XmlIsWellFormed.WellFormed.is_well_formed ~s(<a b=""c=""/>)
3437- fatal: {whitespace_required_between_attributes}
false

iex> XmlIsWellFormed.WellFormed.is_well_formed ~s(<a b="" c=""/>)
true

然而,catchrescue例外情况在Elixir中非常罕见。您应该使用监督树来设计应用程序,以便它知道如何正确地重新生成自己。然后你可以let it crash,主管将负责其余的工作。

相关问题