一、基础语法
1.直接以字符串形式获取nokogiri对象:
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>")
这里的html_doc和xml_doc就是nokogiri文件
2.也可以通过文件句柄获取nokogiri对象:
f = File.open("blossom.xml")doc = Nokogiri::XML(f)f.close
3.还可以直接从网站获取:
require 'open-uri'doc = Nokogiri::HTML(open("http:///')
为了让namespace的使用更方便,nokogiri会自动绑定在根结点上找到的合适的任何namespace.
nokogiri会自动关联提供的URL,这个惯例可以减少代码量.
例如有这样一个atom.xml文件:
<feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://example.org/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://example.org/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry></feed>
遵循上面提到的惯例,xmlns已被自动绑定,不用再手动为xmlns赋值:
@doc.xpath('//xmlns:title')# => ["<title>Example Feed</title>", "<title>Atom-Powered Robots Run Amok</title>"]
同样情况,css的用法:
@doc.css('xmlns|title')
并且在使用css方式时,如果namespaces名字是xmlns,那么连这个词本身都可以忽略掉:
@doc.css('title')