Ruby是一款对开发版本依赖度很高的语言,而且目前不支持中文(如果要使用中文字符,可使用UTF-8)
以下程序在 Ruby 1.8.6 下编译通过, IDE环境为 RubyMine [比NetBean好用]
# 解析XML文件
require "rexml/document"
include REXML
puts "-- BEGIN --"
doc = Document.new(File.open("TestXML.xml"))
#doc.elements.each('BoardComposant') do |elem|
# cr_ele = elem.get_elements('ComponantRectangle')
# puts cr_ele
#end
doc.elements.each("BoardComposant/ComponantRectangle"){ |elem|
if "second" == elem.attributes["name"] then
puts " => 2th"
puts elem.elements[2].elements["Height"].text
elem.elements.each{ |e|
puts e.elements["Height"].text
}
end
}
#----------------------------------------------
puts "-----------------------------------------"
#----------------------------------------------
input = File.new("book.xml")
doc = Document.new(input)
root = doc.root
puts root.attributes["shelf"] # Recent Acquisitions
doc.elements.each("library/section") { |e| puts e.attributes["name"] }
# Output:
# Ruby
# Space
doc.elements.each("*/section/book") { |e| puts e.attributes["isbn"] }
# Output:
# 0672328844
# 0321445619
# 0684835509
# 074325631X
sec2 = root.elements[2]
author = sec2.elements[1].elements["author"].text # Robert Zubrin
puts author
puts "-- End --"
以下是待解析的XML文件
book.xml
The Ruby Way
Hal Fulton
Second edition. The book you are now reading.
Ain't recursion grand
The Case for Mars
Robert Zubrin
Pushing toward a second home for the human
race.
First Man: The Life of Neil A. Armstrong
James R. Hansen
Definitive biography of the first man on
the moon.
TestXML.xml
< xml version="1.0" encoding="utf-8" >
147
219
76
86
510
236
65
77
194
380
108
83
417
400
85
167
770
221
78
70
916
259
68
92
839
416
109
62
953
410
85
63
179
658
108
133
最后show一下我的RubyMine 嘿嘿~~~
