开发者

Using ruby/nokogiri to transform xml to another xml

I've never encountered task of transforming XML from one form to another. I hear that XSLT is just for that, but I don't want to go there. So, using only ruby and nokogiri, how can I:

remove all item elements but time from initial XML and also rename element time to HammerTime?

Initial XML:

...
<item>
  <time>05.04.2011 9:53:23</time>
  <iddqd>42</iddqd>
  <idkfa>woot</idkfa>
</item>
<item>
...

Desired result:

...
<item>
  <HammerTime>05.04.2011 9:53:23</HammerTime>
</item>
<item>
...

I figured out how to put data from XML to array using nokogiri's .xpath, but is there a way to make the desired transformation into another XML without 开发者_C百科manually having to write something like puts "<HammerTime>#{array['time']}</HammerTime>"?


Here you go:

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::HTML <<-EOHTML
<html>
  <body>
    <item>
      <time>05.04.2011 9:53:23</time>
      <iddqd>42</iddqd>
      <idkfa>woot</idkfa>
    </item>
  </body>
</html>
EOHTML

hammer = doc.at_css "time"
hammer.name = 'hammertime'
doc.css("iddqd").remove
doc.css("idkfa").remove

outfile = File.new("output.html", "w")
outfile.puts doc.to_html
outfile.close


What do you mean with

into another XML without manually having to write something like puts "<HammerTime>#{array['time']}</HammerTime>"?

If you want to transform an XML element into another in a language-independent way, you can use XSLT transformations (or stylesheet). Once you have your XSLT file you can apply it with Nokogiri's Nokogiri::XSLT::Stylesheet#apply_to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜