Ruby的XML格式数据解析库Nokogiri的使用进阶


一、基础语法
1.直接以字符串形式获取nokogiri对象:

html_doc = Nokogiri::HTML("

Mr. Belvedere Fan Club

") xml_doc = Nokogiri::XML("Alf")

这里的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://www.xxx.com/"))

二、XML文件解析实例
从XML/HTML文件里抓取字段的常用方法:

现在有一个名为shows.xml的文件,内容如下:


 
  
   Married with Children
   
    Al Bundy
    Bud Bundy
    Marcy Darcy
   
  
  
   Perfect Strangers
   
    Larry Appleton
    Balki Bartokomous
   
  
 
 
  
   The A-Team
   
    John "Hannibal" Smith
    Templeton "Face" Peck
    "B.A." Baracus
    "Howling Mad" Murdock
   
  
 

如果想把所有character标签的内容查找出来,可以这样处理:

@doc = Nokogiri::XML(File.open("shows.xml"))
@doc.xpath("//character")

xpath和css方法,返回的是一个结点列表,类似于一个数组,它的内容就是从文件中查找出来的符合匹配规则的结点.

把dramas结点里的character结点列表查出来:

@doc.xpath("//dramas//character")

更有可读性的css方法:

characters = @doc.css("sitcoms name")
# => ["Married with Children", "Perfect Strangers"]

当已知查询结果唯一时,如果想直接返回这个结果,而不是列表,可以直接使用at_xpath或at_css:

@doc.css("dramas name").first # => "The A-Team"
@doc.at_css("dramas name")  # => "The A-Team"

三、Namespaces
对于有多个标签的情况,命名空间就起到非常大的作用了.
例如有这样一个parts.xml文件:


 
 
  all weather
  studded
  extra wide
 

 
 
  street
  mountain
 


可以使用唯一的URL作为namespaces,以区分不同的tires标签:

@doc = Nokogiri::XML(File.read("parts.xml"))
car_tires = @doc.xpath('//car:tire', 'car' => 'http://alicesautoparts.com/')
bike_tires = @doc.xpath('//bike:tire', 'bike' => 'http://bobsbikes.com/')

为了让namespace的使用更方便,nokogiri会自动绑定在根结点上找到的合适的任何namespace.
nokogiri会自动关联提供的URL,这个惯例可以减少代码量.
例如有这样一个atom.xml文件:



 Example Feed
 
 2003-12-13T18:30:02Z
 
  John Doe
 
 urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6

 
  Atom-Powered Robots Run Amok
  
  urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a
  2003-12-13T18:30:02Z
  Some text.
 


遵循上面提到的惯例,xmlns已被自动绑定,不用再手动为xmlns赋值:

@doc.xpath('//xmlns:title')
# => ["Example Feed", "Atom-Powered Robots Run Amok"]

同样情况,css的用法:

@doc.css('xmlns|title')

并且在使用css方式时,如果namespaces名字是xmlns,那么连这个词本身都可以忽略掉:

@doc.css('title')


你可能感兴趣的:(Ruby的XML格式数据解析库Nokogiri的使用进阶)