开发者

Is it possible to generate plain-old XML using Haml?

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?


Doing XML in HAML is easy, just start off your template with:

!!! XML

which produces

<?xml version='1.0' encoding='utf-8' ?>

Then as @beanish said earlier, you "make up your own tags":

%test
  %test2 hello
  %item{:name => "blah"}

to get

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

More: http://haml.info/docs/yardoc/file.REFERENCE.html#doctype_


%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


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"


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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜