Is it possible to generate plain-old XML using Ham

2020-06-03 02:33发布

I've been working on a piece of software where I need to generate a custom XML file to send back to a client application. The current solutions on Ruby/Rails world for generating XML files are slow, at best. Using builder or event Nokogiri, while have a nice syntax and are maintainable solutions, they consume too much time and processing.

I definetly could go to ERB, which provides a good speed at the expense of building the whole XML by hand.

HAML is a great tool, have a nice and straight-forward syntax and is fairly fast. But I'm struggling to build pure XML files using it. Which makes me wonder, is it possible at all?

Does any one have some pointers to some code or docs showing how to do this, build a full, valid XML from HAML?

7条回答
beautiful°
2楼-- · 2020-06-03 03:12

I've not used HAML, but if you can't make it work another option is Builder.

查看更多
一纸荒年 Trace。
3楼-- · 2020-06-03 03:14

Haml can produce XML just as easily as HTML (I've used it for FBML and XHTML). What problems are you having?

查看更多
我命由我不由天
4楼-- · 2020-06-03 03:20

what about creating the xml header, e.g. <?xml version="1.0" encoding="UTF-8"?> ?

查看更多
Explosion°爆炸
5楼-- · 2020-06-03 03:25

It should be possible. After all you can create plain old XML with Notepad.

查看更多
爷、活的狠高调
6楼-- · 2020-06-03 03:26

This demonstrates some things that could use useful for xml documents:

!!! XML
%root{'xmlns:foo' => 'http://myns'}
  -# Note: :dashed-attr is invalid syntax
  %dashed-tag{'dashed-attr' => 'value'} Text
  %underscore_tag Text
  - ['apple', 'orange', 'pear'].each do |fruit|
    - haml_tag(fruit, "Yummy #{fruit.capitalize}!", 'fruit-code' => fruit.upcase)
  %foo:nstag{'foo:nsattr' => 'value'}

Output:

<?xml version='1.0' encoding='utf-8' ?>
<root xmlns:foo='http://myns'>
  <dashed-tag dashed-attr='value'>Text</dashed-tag>
  <underscore_tag>Text</underscore_tag>
  <apple fruit-code='APPLE'>Yummy Apple!</apple>
  <orange fruit-code='ORANGE'>Yummy Orange!</orange>
  <pear fruit-code='PEAR'>Yummy Pear!</pear>
  <foo:nstag foo:nsattr='value'></foo:nstag>
</root>

Look at the Haml::Helpers link on the haml reference for more methods like haml_tag.

If you want to use double-quotes for attributes,

See: https://stackoverflow.com/a/967065/498594

Or outside of rails use:

>> Haml::Engine.new("%tag{:name => 'value'}", :attr_wrapper => '"').to_html
=> "<tag name=\"value\"></tag>\n"
查看更多
聊天终结者
7楼-- · 2020-06-03 03:33
%test
  %test2 hello
  %item{:name => "blah"}

run it through haml

haml hamltest.haml test.xml

open the file in a browser

<test>
  <test2>hello</test2>
  <item name='blah'></item>
</test>

The HAML reference talks about html tags and gives some examples. HAML reference

查看更多
登录 后发表回答