使用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
新聞熱點
疑難解答