国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Ruby > 正文

Ruby使用REXML庫(kù)來(lái)解析xml格式數(shù)據(jù)的方法

2020-02-24 15:38:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

ReXML是一個(gè)完全用Ruby編寫的處理器,它有許多API,其中有兩個(gè)以類DOM和類SAX進(jìn)行區(qū)分,下面就跟著武林技術(shù)頻道小編的步伐來(lái)學(xué)習(xí)Ruby使用REXML庫(kù)來(lái)解析xml格式數(shù)據(jù)的方法。
rexml具有如下特點(diǎn):

  • 100%用ruby編寫
  • 可以用來(lái)解析SAX和DOM
  • 輕量,不足2000行代碼
  • 提供完整的API支持
  • ruby中內(nèi)置

下面我們來(lái)看看如何使用它,假設(shè)我們有如下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 REXMLxmlfile = File.new("movies.xml")xmldoc = Document.new(xmlfile)root = xmldoc.rootputs "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 REXMLxmlfile = File.new("movies.xml")xmldoc = Document.new(xmlfile)movie = XPath.first(xmldoc, "http://movie")p movieXPath.each(xmldoc, "http://type") { |e| puts e.text }names = XPath.match(xmldoc, "http://format").map {|x| x.text }p names

以備不時(shí)之需!

PS:關(guān)于REXML的安全問題
Ruby官方網(wǎng)站在8月23日發(fā)布了安全通告:http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/,在Ruby當(dāng)前使用的XML解析庫(kù)REXML在解析具有嵌套遞歸元素的XML文件的時(shí)候,將會(huì)出現(xiàn)拒絕服務(wù)攻擊的缺陷,導(dǎo)致服務(wù)器資源耗盡!
凡是在Rails應(yīng)用程序當(dāng)中使用到了XML文件解析功能的都存在上述缺陷,需要進(jìn)行修復(fù)。在Rails當(dāng)中的修復(fù)辦法如下:
1、Rails2.0.2和以前的老版本
下載修復(fù)文件,拷貝到RAILS_ROOT/lib目錄下,并且在environment.rb當(dāng)中加入語(yǔ)句

require ‘rexml-expansion-fix'

2、Rails 2.1.0以上版本
下載修復(fù)文件,拷貝到RAILS_ROOT/config/initializers目錄下即可。

Ruby使用REXML庫(kù)來(lái)解析xml格式數(shù)據(jù)的方法今天就為大家介紹到這里了,由于篇幅的有限,我們就為大家介紹這些。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 漳浦县| 肇州县| 凌海市| 汽车| 梨树县| 靖江市| 万宁市| 晴隆县| 隆林| 东辽县| 醴陵市| 夏河县| 洱源县| 平乐县| 秭归县| 诸城市| 安达市| 东宁县| 泰来县| 棋牌| 彰武县| 温泉县| 大渡口区| 尤溪县| 昌宁县| 历史| 宁都县| 江永县| 科技| 察隅县| 漳浦县| 绵阳市| 寻甸| 内江市| 普兰店市| 眉山市| 屏南县| 福泉市| 安溪县| 游戏| 建德市|