返回顶部

收藏

ruby解析xml代码示例

更多

如下代码用ruby的libxml-ruby来解析xml。

 %w[rubygems libxml xml].each { |x11| require x11 }
doc = XML::Document.file("posts.xml")
nodes =  doc.find("posts")
#puts nodes.length
#puts nodes[0]
nodes.each do |node|
 #puts node
 if node[:user] == 'jnunemaker1'
  itemnodes = node.find("post")
  if itemnodes
   itemnodes.each do |itemnode|
      puts 'href: '+itemnode[:href]
      puts 'hash: '+ itemnode[:hash]
      puts 'description: '+ itemnode[:description]
      puts 'tag: '+ itemnode[:tag]
      puts 'time: '+ itemnode[:time]
      puts 'others: '+ itemnode[:others]
      puts'*************'
    end
   end

 end
end

对应的解析的xml文件代码

<message>
 <posts user="jnunemaker1" tag="ruby"> 
   <post href="http://roxml.rubyforge.org/" hash="19bba2ab667be03a19f67fb67dc56917" description="ROXML - Ruby Object to XML Mapping Library" tag="ruby xml gems mapping" time="2008-08-09T05:24:20Z" others="56" extended="ROXML is a Ruby library designed to make it easier for Ruby developers to work with XML. Using simple annotations, it enables Ruby classes to be custom-mapped to XML. ROXML takes care of the marshalling and unmarshalling of mapped attributes so that developers can focus on building first-class Ruby classes."/> 
   <post href="http://code.google.com/p/sparrow/" hash="1df8a7cb9e8960992556518c0ea0d146" description="sparrow - Google Code" tag="ruby sparrow memcache queue" time="2008-08-06T15:07:24Z" others="115" extended="Sparrow is a really fast lightweight queue written in Ruby that speaks memcache. That means you can use Sparrow with any memcached client library (Ruby or otherwise)."/> 
   </posts> 
 <!-- fe04.api.del.ac4.yahoo.net uncompressed/chunked Sat Aug  9 00:20:11 PDT 2008 -->

 <posts user="jnunemaker2" tag="ruby"> 
 <post href="http://labs.reevoo.com/plugins/beanstalk-messaging" hash="d100c10208acbf5e954320a5577838d9" description="reevoolabs - Beanstalk Messaging" tag="railstips messaging queue rails ruby" time="2008-07-28T02:57:00Z" others="33" extended="Good write up on beanstalk"/> 
   <post href="http://www.slideshare.net/guest807bb2/rubyfringe?src=embed" hash="c3dc3b940dbe25e39737240b4e1ab071" description="Rockstar Memcached" tag="memcached performance caching ruby rails railstips" time="2008-07-28T02:30:50Z" others="11" extended="Killer presentation on memcached by Tobi of Shopify."/> 
   <post href="http://www.igvita.com/2008/07/22/unix-signals-for-live-debugging/" hash="288054a38d870b15bdf060ed5c6b2a2e" description="Unix Signals for Live Debugging - igvita.com" tag="ruby signals unix debugging signal railstips" time="2008-07-27T04:53:00Z" others="86" extended="I've known how to kill processes and such but never quite understood kill. Ilya Grigorik explains not only how to send those signals but how to use them in your scripts to change the way they behave on the fly. Very cool."/>
   </posts>
</message>

标签:ruby,xml

收藏

0人收藏

支持

0

反对

0