用户登录
用户注册

分享至

Ruby使用REXML库来解析xml格式数据的方法

  • 作者: 利多卡因2812997
  • 来源: 51数据库
  • 2021-08-29

rexml 是一个完全用ruby写的processor ,他有多种api,其中两个经典的api是通过dom-like 和sax-like 来进行区分的。第一种是将整个文件读进内存,然后存储为一个分层的形式(也就是一棵树了).而第二种是"parse as you go",当你的文件很大,并且内存受到限制的时候,比较适合用这种。
rexml具有如下特点:

  • 100%用ruby编写
  • 可以用来解析sax和dom
  • 轻量,不足2000行代码
  • 提供完整的api支持
  • ruby中内置

下面我们来看看如何使用它,假设我们有如下xml文件:

<collection shelf="new arrivals">
 <movie title="enemy behind">
 <type>war, thriller</type>
 <format>dvd</format>
 <year>2003</year>
 <rating>pg</rating>
 <stars>10</stars>
 <description>talk about a us-japan war</description>
 </movie>
 <movie title="transformers">
 <type>anime, science fiction</type>
 <format>dvd</format>
 <year>1989</year>
 <rating>r</rating>
 <stars>8</stars>
 <description>a schientific fiction</description>
 </movie>
 <movie title="trigun">
 <type>anime, action</type>
 <format>dvd</format>
 <episodes>4</episodes>
 <rating>pg</rating>
 <stars>10</stars>
 <description>vash the stampede!</description>
 </movie>
 <movie title="ishtar">
 <type>comedy</type>
 <format>vhs</format>
 <rating>pg</rating>
 <stars>2</stars>
 <description>viewable boredom</description>
 </movie>
</collection>

解析dom:

require 'rexml/document'
include rexml
xmlfile = file.new("movies.xml")
xmldoc = document.new(xmlfile)
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
}

使用xpath:

require 'rexml/document'
include rexml
xmlfile = file.new("movies.xml")
xmldoc = document.new(xmlfile)
movie = xpath.first(xmldoc, "//movie")
p movie
xpath.each(xmldoc, "//type") { |e| puts e.text }
names = xpath.match(xmldoc, "//format").map {|x| x.text }
p names

以备不时之需!

ps:关于rexml的安全问题
ruby官方网站在8月23日发布了安全通告:http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/,在ruby当前使用的xml解析库rexml在解析具有嵌套递归元素的xml文件的时候,将会出现拒绝服务攻击的缺陷,导致服务器资源耗尽!
凡是在rails应用程序当中使用到了xml文件解析功能的都存在上述缺陷,需要进行修复。在rails当中的修复办法如下:
1、rails2.0.2和以前的老版本
下载,拷贝到rails_root/lib目录下,并且在environment.rb当中加入语句

require ‘rexml-expansion-fix'

2、rails 2.1.0以上版本
下载,拷贝到rails_root/config/initializers目录下即可。

软件
前端设计
程序设计
Java相关