在Ruby中处理XML和XSLT以及XPath的简单教程

2019-09-25 09:45:59于丽

DOM 解析器

让我们先来解析 XML 数据,首先我们先引入 rexml/document 库,通常我们可以将 REXML 在顶级的命名空间中引入:

#!/usr/bin/ruby -w
 
require 'rexml/document'
include REXML
 
xmlfile = File.new("movies.xml")
xmldoc = Document.new(xmlfile)
 
# 获取 root 元素
root = xmldoc.root
puts "Root element : " + root.attributes["shelf"]
 
# 以下将输出电影标题
xmldoc.elements.each("collection/movie"){
  |e| puts "Movie Title : " + e.attributes["title"]
}
 
# 以下将输出所有电影类型
xmldoc.elements.each("collection/movie/type") {
  |e| puts "Movie Type : " + e.text
}
 
# 以下将输出所有电影描述
xmldoc.elements.each("collection/movie/description") {
  |e| puts "Movie Description : " + e.text
}

以上实例输出结果为:

Root element : New Arrivals
Movie Title : Enemy Behind
Movie Title : Transformers
Movie Title : Trigun
Movie Title : Ishtar
Movie Type : War, Thriller
Movie Type : Anime, Science Fiction
Movie Type : Anime, Action
Movie Type : Comedy
Movie Description : Talk about a US-Japan war
Movie Description : A schientific fiction
Movie Description : Vash the Stampede!
Movie Description : Viewable boredom
SAX-like Parsing:

SAX 解析器

处理相同的数据文件:movies.xml,不建议SAX的解析为一个小文件,以下是个简单的实例:

#!/usr/bin/ruby -w
 
require 'rexml/document'
require 'rexml/streamlistener'
include REXML
 
 
class MyListener
 include REXML::StreamListener
 def tag_start(*args)
  puts "tag_start: #{args.map {|x| x.inspect}.join(', ')}"
 end
 
 def text(data)
  return if data =~ /^w*$/   # whitespace only
  abbrev = data[0..40] + (data.length > 40 ? "..." : "")
  puts " text  :  #{abbrev.inspect}"
 end
end
 
list = MyListener.new
xmlfile = File.new("movies.xml")
Document.parse_stream(xmlfile, list)

以上输出结果为:

tag_start: "collection", {"shelf"=>"New Arrivals"}
tag_start: "movie", {"title"=>"Enemy Behind"}
tag_start: "type", {}
 text  :  "War, Thriller"
tag_start: "format", {}
tag_start: "year", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
 text  :  "Talk about a US-Japan war"
tag_start: "movie", {"title"=>"Transformers"}
tag_start: "type", {}
 text  :  "Anime, Science Fiction"
tag_start: "format", {}
tag_start: "year", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
 text  :  "A schientific fiction"
tag_start: "movie", {"title"=>"Trigun"}
tag_start: "type", {}
 text  :  "Anime, Action"
tag_start: "format", {}
tag_start: "episodes", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
 text  :  "Vash the Stampede!"
tag_start: "movie", {"title"=>"Ishtar"}
tag_start: "type", {}
tag_start: "format", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
 text  :  "Viewable boredom"