Ruby中使用Nokogiri包來操作XML格式數(shù)據(jù)的教程
安裝
對(duì)于Ubuntu,需要安裝好 libxml2, libxslt 這兩個(gè)組件:
$ apt-get install libxml2 libxslt
然后就可以:
$ gem install nokogiri
可選項(xiàng)
nokogiri提供了一些解析文件時(shí)的可選項(xiàng),常用的有:
- NOBLANKS : 刪除空節(jié)點(diǎn)
- NOENT : 替代實(shí)體
- NOERROR : 隱藏錯(cuò)誤報(bào)告
- STRICT : 精確解析,當(dāng)解析到文件異常時(shí)拋出錯(cuò)誤
- NONET : 在解析期間禁止任何網(wǎng)絡(luò)連接.
可選項(xiàng)使用方式舉例(通過塊調(diào)用):
doc = Nokogiri::XML(File.open("blossom.xml")) do |config| config.strict.nonet end
或者
doc = Nokogiri::XML(File.open("blossom.xml")) do |config| config.options = Nokogiri::XML::ParseOptions::STRICT | Nokogiri::XML::ParseOptions::NONET end
解析
可以從文件,字符串,URL等來解析??康氖沁@兩個(gè)方法 Nokogiri::HTML, Nokogiri::XML:
讀取字符串:
html_doc = Nokogiri::HTML("<html><body><h1>Mr. Belvedere Fan Club</h1></body></html>") xml_doc = Nokogiri::XML("<root><aliens><alien><name>Alf</name></alien></aliens></root>")
讀取文件:
f = File.open("blossom.xml") doc = Nokogiri::XML(f) f.close
讀取URL:
require 'open-uri' doc = Nokogiri::HTML(open("http://www.threescompany.com/"))
尋找節(jié)點(diǎn)
可以使用XPATH 以及 CSS selector 來搜索: 例如,給定一個(gè)XML:
<books> <book> <title>Stars</title> </book> <book> <title>Moon</title> </book> </books>
xpath:
@doc.xpath("http://title")
css:
@doc.css("book title")
修改節(jié)點(diǎn)內(nèi)容
title = @doc.css("book title").firsto title.content = 'new title' puts @doc.to_html # => ... <title>new title</title> ...
修改節(jié)點(diǎn)的結(jié)構(gòu)
first_title = @doc.at_css('title') second_book = @doc.css('book').last # 可以把第一個(gè)title放到第二個(gè)book中 first_title.parent = second_book # 也可以隨意擺放。 second_book.add_next_sibling(first_title) # 也可以修改對(duì)應(yīng)的class first_title.name = 'h2' first_title['class']='red_color' puts @doc.to_html # => <h2 class='red_color'>...</h2> # 也可以新建一個(gè)node third_book = Nokogiri::XML::Node.new 'book', @doc third_book.content = 'I am the third book' second_book.add_next_sibling third_book puts @doc.to_html # => ... <books> ... <book>I am the third book</book> </books>
相關(guān)文章
Ruby實(shí)現(xiàn)的一個(gè)強(qiáng)大的批量刪除文件腳本分享
這篇文章主要介紹了Ruby實(shí)現(xiàn)的一個(gè)強(qiáng)大的批量刪除文件腳本分享,本文腳本實(shí)現(xiàn)對(duì)指定目錄下的文件根據(jù)最后修改時(shí)間刪除文件,需要的朋友可以參考下2015-01-01Windows下Ruby on Rails開發(fā)環(huán)境安裝配置圖文教程
這篇文章主要介紹了Windows下Ruby on Rails開發(fā)環(huán)境安裝配置圖文教程,ROR初學(xué)者必看,需要的朋友可以參考下2014-07-07Ruby使用GDBM操作DBM數(shù)據(jù)存儲(chǔ)方法實(shí)例詳解
這篇文章主要介紹了Ruby使用GDBM操作DBM數(shù)據(jù)存儲(chǔ)方法實(shí)例詳解,需要的朋友可以參考下2022-04-04Ruby中實(shí)現(xiàn)統(tǒng)計(jì)文件行數(shù)、單詞數(shù)和字符數(shù)
這篇文章主要介紹了Ruby中實(shí)現(xiàn)統(tǒng)計(jì)文件行數(shù)、單詞數(shù)和字符數(shù),本文是自定義的一個(gè)函數(shù),需要的朋友可以參考下2015-01-01Ruby程序中發(fā)送基于HTTP協(xié)議的請(qǐng)求的簡(jiǎn)單示例
這篇文章主要介紹了Ruby程序中發(fā)送基于HTTP協(xié)議的請(qǐng)求的簡(jiǎn)單示例,包括對(duì)HTTPS請(qǐng)求的介紹,需要的朋友可以參考下2016-03-03