如何使用Nokogiri SAX Parser检索XML元素的值?

时间:2015-03-18 17:50:09

标签: ruby xml nokogiri sax

如何使用Nokogiri SAX解析器访问嵌套元素的文本值?

require 'nokogiri'

  xml = <<-eos
   <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      <sitemap>
        <loc>http://www.example.com/example-sitemap.xml</loc>
     </sitemap>
    </sitemapindex>
  eos

  class MySAXDoc < Nokogiri::XML::SAX::Document
     def start_element name, attrs=[]
        if name == "sitemap"
          # from here, how can one retrieve the value of the child element, `loc`?
        end
     end
  end

  sax_parser = Nokogiri::XML::SAX::Parser.new(MySAXDoc.new)
  sax_parser.parse(xml)

1 个答案:

答案 0 :(得分:2)

您无法提前阅读,因此您必须自己跟踪文件中的当前上下文。沿着这些方向的东西可以解决这个问题:

def start_element(name, attrs = [])
  @element = name

  if name == 'sitemap'
    @sitemap = true
  end
end

def end_element(name)
  @element = nil

  if name == 'sitemap'
    @sitemap = false
  end
end

def characters(string)
  if @element == 'loc' && @sitemap
    # The local variable 'string' holds the text contents of the <loc> tag
    # so do something with it here
    puts string
  end
end

如何工作:当一个新元素启动时,它会检查它是否为a,如果是,则设置一个@sitemap变量。在元素的下一次迭代中,它检查@sitemap以查看它是否在站点地图中并对其内容执行某些操作。

相关问题