REXML 是由 Sean Russell 編寫(xiě)的庫(kù)。它不是 Ruby 的唯一 XML 庫(kù),但它是很受歡迎的一個(gè),并且是用純 Ruby 編寫(xiě)( NQXML 也是用 Ruby 編寫(xiě)的, 但 XMLParser 封裝了用 C 編寫(xiě)的 Jade 庫(kù))。 在他的 REXML 概述中,Russell 評(píng)論道:
我有這樣的問(wèn)題:我不喜歡令人困惑的 API。有幾種用于 Java 實(shí)現(xiàn)的 XML 解析器 API。其中大多數(shù)都遵循 DOM 或 SAX,并且在基本原理上與不斷出現(xiàn)的眾多 Java API 非常相似。也就是說(shuō),它們看 上去象是由從未使用過(guò)他們自己的 API 的理論家設(shè)計(jì)出來(lái)的。 通常,現(xiàn)有的 XML API 都很令人討厭。他們采用一種被明確設(shè)計(jì)成非常簡(jiǎn)單、一流且功能強(qiáng)大的標(biāo)記語(yǔ)言, 然后用討厭的、過(guò)多的和大型 API 對(duì)它進(jìn)行封裝。甚至是為了進(jìn)行最基本的 XML 樹(shù)操作,我總是不得不參考 API 文檔; 沒(méi)有任何東西是憑直覺(jué)的,而且?guī)缀趺總€(gè)操作都很復(fù)雜。
雖然我并不認(rèn)為它有多么令人心煩,但我同意 Russell 的觀點(diǎn):XML API 對(duì)于大多數(shù)使用它們的人來(lái)說(shuō)無(wú)疑帶來(lái)了過(guò)多的工作量。
示例
看下面的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 庫(kù),并且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
這里要注意的是xml中的屬性和值被表示為一個(gè)hash,因此我們能夠通過(guò)attributes[]來(lái)提取我們需要的值,元素的值還能通過(guò)類(lèi)似于path的字符串或者整數(shù)來(lái)取得.其中用整數(shù)取的話,是1-based而不是0-based.
2 Stream Parsing(也就是SAX-like Parsing)
這邊使用了一個(gè)小技巧,那就是定義了一個(gè)listener 類(lèi),它將會(huì)在parse的時(shí)候被回調(diào):
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 source = File.new "books.xml" Document.parse_stream(source, list)
這里介紹一下StreamListener 模塊,這個(gè)模塊它提供了幾個(gè)空的回調(diào)方法,因此你可以為了實(shí)現(xiàn)你自己的功能而覆蓋它.當(dāng)parser 進(jìn)入一個(gè)tag時(shí),就會(huì)調(diào)用tag_start方法.而text方法也是類(lèi)似的,他只不過(guò)是當(dāng)讀取到數(shù)據(jù)時(shí)會(huì)被回調(diào),它的輸出是這樣的:
tag_start: "library", {"shelf"=>"Recent Acquisitions"} tag_start: "section", {"name"=>"Ruby"} tag_start: "book", {"isbn"=>"0672328844"} tag_start: "title", {} text : "The Ruby Way"
3 XPath
REXML通過(guò)XPath 類(lèi)來(lái)提供Xpath的支持. 它也同時(shí)支持DOM-like和SAX-like .還是前面的那個(gè)xml文件,我們使用Xpath可以這樣做:
book1 = XPath.first(doc, "http://book") # Info for first book found p book1 # Print out all titles XPath.each(doc, "http://title") { |e| puts e.text } # Get an array of all of the "author" elements in the document. names = XPath.match(doc, "http://author").map {|x| x.text } p names
輸出是類(lèi)似于下面的:
book isbn='0672328844'> ... /> The Ruby Way The Case for Mars First Man: The Life of Neil A. Armstrong ["Hal Fulton", "Robert Zubrin", "James R. Hansen"]
標(biāo)簽:松原 宜春 淄博 自貢 鄂州 六安 石嘴山 河北
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《實(shí)例解析Ruby程序中調(diào)用REXML來(lái)解析XML格式數(shù)據(jù)的用法》,本文關(guān)鍵詞 實(shí)例,解析,Ruby,程序,中,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。