简体   繁体   English

如何在 Elixir 中将 xml 转换为地图?

[英]How to convert xml to a map in Elixir?

Rails extends Hash with from_xml Rails 使用 from_xml 扩展 Hash

xml = <<-XML
  <?xml version="1.0" encoding="UTF-8"?>
    <hash>
      <foo type="integer">1</foo>
      <bar type="integer">2</bar>
    </hash>
XML

hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}

I'm struggling to find any examples for how to do this in Elixir in a comparably easy way.我正在努力寻找任何关于如何以相对简单的方式在 Elixir 中执行此操作的示例。

Something like:就像是:

Map.from_xml(xml)
# => %{"hash" => %{"foo" => 1, "bar" => 2}}

I looked at sweet_xml, which has some nice sigils for pulling out specific patterns of data.我查看了 sweet_xml,它有一些很好的符号可以提取特定的数据模式。 My issue with it that, it requires a pretty verbose setup on my part in order to specify all the paths I would need to get.我的问题是,它需要我进行非常详细的设置才能指定我需要获取的所有路径。

I also looked at Quinn, which parses xml into some other data structure which can be searched.我还查看了 Quinn,它将 xml 解析为其他一些可以搜索的数据结构。 I find intermediate data structures a bit weird to work with compared to a map.与地图相比,我发现使用中间数据结构有点奇怪。

The other issue is that both these libraries use xmerl, which looks like it creates new atoms from the xml it is parsing.另一个问题是这两个库都使用了 xmerl,看起来它从正在解析的 xml 中创建了新的原子。

I decided to scratch my own itch as an exercise to see if I could and create my first hex package: https://github.com/homanchou/elixir-xml-to-map我决定将自己的痒作为练习,看看我是否可以创建我的第一个十六进制包: https ://github.com/homanchou/elixir-xml-to-map

It uses the erlsom erlang library behind the scenes which says that it uses string keys instead, which I think is safer since atoms are not garbage collected.它在幕后使用 erlsom erlang 库,它说它使用字符串键,我认为这更安全,因为原子不会被垃圾收集。

Given the response to this question it's apparently extremely taboo to even consider using this naive approach, so use with caution.鉴于对这个问题的回答,甚至考虑使用这种幼稚的方法显然是极其禁忌的,因此请谨慎使用。 The Readme details the shortcomings.自述文件详细说明了缺点。

Try to use sweet_xml .尝试使用sweet_xml You can return a map from the xml document using xmap function and basic usage of xpath.您可以使用xmap函数和 xpath 的基本用法从 xml 文档返回地图。 Here's an example .这是一个例子

还有一种基于SAX (XML 的简单 API)算法的工具: https ://github.com/xinz/sax_map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM