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

首頁 > 學院 > 開發設計 > 正文

Ruby程序中創建和解析XML文件的方法

2019-10-26 19:28:32
字體:
來源:轉載
供稿:網友

使用builder創建XML

builder安裝方法:

gem install builder
require 'builder'   x = Builder::XmlMarkup.new(:target => $stdout, :indent => 1) #":target =>$stdout"參數:指示輸出內容將被寫向標準輸出控制臺 #":indent =>1"參數:XML輸出形式將被縮進一個空格字符x.instruct! :xml,:version =>'1.1',:encoding => 'gb2312' x.comment! "書本信息"  x.library("shelf" => "Recent Acquisitions") { x.section("name" => "ruby"){ x.book("isbn" => "0672310001"){ x.title "Programming Ruby"  x.author "Yukihiro " x.description "Programming Ruby - The Pragmatic Programmer's Guide" } } } 

p x #打印XML

Ruby創建XML輸出結果:

< ?xml version="1.1" encoding="gb2312"?> < !-- 書本信息 --> < library shelf="Recent Acquisitions"> < section name="ruby"> < book isbn="0672310001"> < title>Programming Ruby< /title> < author>Yukihiro < /author> < description>Programming Ruby - The Pragmatic Programmer's Guide< /description> < /book> < /section> < /library> < inspect/> #< IO:0x2a06ae8> 

使用ReXML解析XML

REXML 是一個完全用ruby寫的processor ,他有多種api,其中兩個經典的api是通過DOM-like 和SAX-like 來進行區分的。第一種是將整個文件讀進內存,然后存儲為一個分層的形式(也就是一棵樹了).而第二種是"parse as you go",當你的文件很大,并且內存受到限制的時候,比較適合用這種。

看下面的book.xml:

引用

<library shelf="Recent Acquisitions">   <section name="Ruby">     <book isbn="0672328844">     <title>The Ruby Way</title>     <author>Hal Fulton</author>     <description>       Second edition. The book you are now reading.       Ain't recursion grand?     </description>     </book>   </section>   <section name="Space">     <book isbn="0684835509">       <title>The Case for Mars</title>       <author>Robert Zubrin</author>       <description>Pushing toward a second home for the human         race.       </description>     </book>     <book isbn="074325631X">       <title>First Man: The Life of Neil A. Armstrong</title>       <author>James R. Hansen</author>       <description>Definitive biography of the first man on         the moon.       </description>     </book>   </section> </library>


1 Tree Parsing(也就是DOM-like)

我們需要require rexml/document 庫,并且include REXML :

require 'rexml/document' include REXML  input = File.new("books.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             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 清徐县| 青田县| 民县| 洛南县| 夹江县| 峨山| 米易县| 东乡| 漠河县| 泰来县| 尤溪县| 舞钢市| 元谋县| 崇阳县| 新建县| 双流县| 准格尔旗| 鹤山市| 澄迈县| 安西县| 樟树市| 合阳县| 固阳县| 贡觉县| 沙雅县| 望奎县| 双牌县| 连江县| 梅河口市| 夹江县| 浮山县| 宁津县| 当涂县| 漠河县| 城固县| 巴彦县| 安阳县| 方城县| 盐山县| 西丰县| 新营市|