SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 224 | Next

Ola Bini

"Practical JRuby on Rails Web 2.0 Projects: Bringing Ruby on Rails to Java"

Further, it doesn??™t work in JRuby, so I won??™t cover it at all in
this book. The third approach??”which this section is about??”is called REXML, and it??™s part of the
Ruby standard distribution. It conforms to XML 1.0, but it doesn??™t do validation.
A simple test program will show you how to walk all the nodes in the file and print their
names and attributes (see Listing 8-1).
Listing 8-1. rexml_print.rb
require 'rexml/document'
include REXML
input = File.new(ARGV[0])
doc = Document.new input
def print_element(el, indent=0)
print " "*indent
print el.name
if el.attributes.size > 0
print ": #{el.attributes.map{|k,v| "#{k}=>#{v}"}}"
end
if el.text && el.text.strip.size > 0
print ": #{el.text.strip}"
end
puts
el.elements.each { |e|
print_element(e,indent+2)
}
end
doc.elements.each { |e|
print_element e
}
You can run the file like this:
jruby rexml_print.rb projects.xml
This would generate output that looks like this:
company
projects
project: id=>shoplet
CHAPTER 8 ?–  CONTENT RENDERING 145
title: The Store: Shoplet
description: The Shoplet application is supposed to
teach the reader about basic Rails functionality.
manager: ref=>hmank
project: id=>compose
title: CoMpoSe: Content made easy
description: CoMpoSe is a content management system,
based on high tech buzzwords like XML, RedCloth and Rails.
manager: ref=>slars
manager: ref=>adahl
project: id=>bigbrother
title: Big Brother, administration in a nutshell
description: Big Brother is the swiss army knife of administration tools
manager: ref=>adahl
managers
manager: id=>adahl: Arne Dahl
manager: id=>hmank: Henning Mankell
manager: id=>slars: Stieg Larsson
I??™ll briefly walk you through what??™s happening here: you walk the XML Document Object
Model (DOM), printing text if there is any, attributes if any, and all sub-elements.


Pages:
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236