- Ruby 基礎
- Ruby - 首頁
- Ruby - 概述
- Ruby - 環境設定
- Ruby - 語法
- Ruby - 類和物件
- Ruby - 變數
- Ruby - 運算子
- Ruby - 註釋
- Ruby - IF...ELSE
- Ruby - 迴圈
- Ruby - 方法
- Ruby - 程式碼塊
- Ruby - 模組
- Ruby - 字串
- Ruby - 陣列
- Ruby - 雜湊表
- Ruby - 日期和時間
- Ruby - 範圍
- Ruby - 迭代器
- Ruby - 檔案 I/O
- Ruby - 異常
Ruby - XML、XSLT和XPath 教程
什麼是 XML?
可擴充套件標記語言 (XML) 是一種標記語言,類似於 HTML 或 SGML。這是全球資訊網聯盟推薦的開放標準。
XML 是一種可移植的開源語言,允許程式設計師開發可被其他應用程式讀取的應用程式,而不管作業系統和/或開發語言如何。
XML 在無需基於 SQL 的後端的情況下跟蹤少量到中等數量的資料方面非常有用。
XML 解析器架構和 API
XML 解析器有兩種不同的型別:
SAX 式 (流介面) - 在這裡,您為感興趣的事件註冊回撥,然後讓解析器處理文件。當您的文件很大或記憶體有限時,這很有用,它在從磁碟讀取檔案時解析檔案,並且整個檔案永遠不會儲存在記憶體中。
DOM 式 (物件樹介面) - 這是全球資訊網聯盟的建議,其中整個檔案被讀入記憶體並存儲在分層(基於樹)的形式中,以表示 XML 文件的所有特徵。
在處理大型檔案時,SAX 的處理速度顯然不如 DOM 快。另一方面,僅使用 DOM 會嚴重影響您的資源,尤其是在處理大量小檔案時。
SAX 是隻讀的,而 DOM 允許更改 XML 檔案。由於這兩種不同的 API 實際上是互補的,因此沒有理由不能將它們都用於大型專案。
使用 Ruby 解析和建立 XML
操作 XML 最常見的方法是使用 Sean Russell 的 REXML 庫。自 2002 年以來,REXML 一直是標準 Ruby 發行版的一部分。
REXML 是一個純 Ruby XML 處理器,符合 XML 1.0 標準。它是一個非驗證處理器,通過了所有 OASIS 非驗證一致性測試。
REXML 解析器與其他可用解析器相比具有以下優點:
- 它完全是用 Ruby 編寫的。
- 它可用於 SAX 和 DOM 解析。
- 它很輕量級,程式碼少於 2000 行。
- 方法和類非常易於理解。
- 基於 SAX2 的 API 和完整的 XPath 支援。
- 隨 Ruby 安裝一起提供,無需單獨安裝。
對於我們所有的 XML 程式碼示例,讓我們使用一個簡單的 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 式解析
讓我們首先以樹狀方式解析我們的 XML 資料。我們首先需要rexml/document庫;通常為了方便,我們會包含 REXML 以匯入到頂層名稱空間中。
#!/usr/bin/ruby -w
require 'rexml/document'
include REXML
xmlfile = File.new("movies.xml")
xmldoc = Document.new(xmlfile)
# Now get the root element
root = xmldoc.root
puts "Root element : " + root.attributes["shelf"]
# This will output all the movie titles.
xmldoc.elements.each("collection/movie"){
|e| puts "Movie Title : " + e.attributes["title"]
}
# This will output all the movie types.
xmldoc.elements.each("collection/movie/type") {
|e| puts "Movie Type : " + e.text
}
# This will output all the movie description.
xmldoc.elements.each("collection/movie/description") {
|e| puts "Movie Description : " + e.text
}
這將產生以下結果:
Root element : New Arrivals Movie Title : Enemy Behind Movie Title : Transformers Movie Title : Trigun Movie Title : Ishtar Movie Type : War, Thriller Movie Type : Anime, Science Fiction Movie Type : Anime, Action Movie Type : Comedy Movie Description : Talk about a US-Japan war Movie Description : A schientific fiction Movie Description : Vash the Stampede! Movie Description : Viewable boredom
SAX 式解析
為了以面向流的方式處理相同的資料(movies.xml)檔案,我們將定義一個監聽器類,其方法將成為解析器中回撥的目標。
注意 - 不建議對小檔案使用 SAX 式解析,這隻用於演示示例。
#!/usr/bin/ruby -w
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
xmlfile = File.new("movies.xml")
Document.parse_stream(xmlfile, list)
這將產生以下結果:
tag_start: "collection", {"shelf"=>"New Arrivals"}
tag_start: "movie", {"title"=>"Enemy Behind"}
tag_start: "type", {}
text : "War, Thriller"
tag_start: "format", {}
tag_start: "year", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
text : "Talk about a US-Japan war"
tag_start: "movie", {"title"=>"Transformers"}
tag_start: "type", {}
text : "Anime, Science Fiction"
tag_start: "format", {}
tag_start: "year", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
text : "A schientific fiction"
tag_start: "movie", {"title"=>"Trigun"}
tag_start: "type", {}
text : "Anime, Action"
tag_start: "format", {}
tag_start: "episodes", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
text : "Vash the Stampede!"
tag_start: "movie", {"title"=>"Ishtar"}
tag_start: "type", {}
tag_start: "format", {}
tag_start: "rating", {}
tag_start: "stars", {}
tag_start: "description", {}
text : "Viewable boredom"
XPath 和 Ruby
檢視 XML 的另一種方法是 XPath。這是一種偽語言,描述瞭如何在 XML 文件中定位特定元素和屬性,並將該文件視為一個邏輯有序的樹。
REXML 透過XPath類支援 XPath。如上所述,它假定基於樹的解析(文件物件模型)。
#!/usr/bin/ruby -w
require 'rexml/document'
include REXML
xmlfile = File.new("movies.xml")
xmldoc = Document.new(xmlfile)
# Info for the first movie found
movie = XPath.first(xmldoc, "//movie")
p movie
# Print out all the movie types
XPath.each(xmldoc, "//type") { |e| puts e.text }
# Get an array of all of the movie formats.
names = XPath.match(xmldoc, "//format").map {|x| x.text }
p names
這將產生以下結果:
<movie title = 'Enemy Behind'> ... </> War, Thriller Anime, Science Fiction Anime, Action Comedy ["DVD", "DVD", "DVD", "VHS"]
XSLT 和 Ruby
Ruby 可以使用兩個可用的 XSLT 解析器。這裡簡要介紹了每個解析器。
Ruby-Sablotron
此解析器由 Takahashi Masayoshi 編寫和維護。它主要為 Linux 作業系統編寫,需要以下庫:
- Sablot
- Iconv
- Expat
您可以在Ruby-Sablotron找到此模組。
XSLT4R
XSLT4R 由 Michael Neumann 編寫,可以在 RAA 的“庫”部分(在 XML 下)找到。XSLT4R 使用簡單的命令列介面,但也可以在第三方應用程式中用於轉換 XML 文件。
XSLT4R 需要 XMLScan 才能執行,後者包含在 XSLT4R 存檔中,並且也是一個 100% 的 Ruby 模組。可以使用標準的 Ruby 安裝方法(即 ruby install.rb)安裝這些模組。
XSLT4R 的語法如下:
ruby xslt.rb stylesheet.xsl document.xml [arguments]
如果您想在應用程式中使用 XSLT4R,您可以包含 XSLT 並輸入所需的引數。這是一個示例:
require "xslt"
stylesheet = File.readlines("stylesheet.xsl").to_s
xml_doc = File.readlines("document.xml").to_s
arguments = { 'image_dir' => '/....' }
sheet = XSLT::Stylesheet.new( stylesheet, arguments )
# output to StdOut
sheet.apply( xml_doc )
# output to 'str'
str = ""
sheet.output = [ str ]
sheet.apply( xml_doc )
進一步閱讀
有關 REXML 解析器的完整詳細資訊,請參閱REXML 解析器文件的標準文件。
您可以從RAA 儲存庫下載 XSLT4R。