如何使用 Nokogiri SAX 解析器检索 XML 元素的值?

How to retrieve value of XML element using a Nokogiri SAX Parser?

如何使用 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)

您无法预读,因此您必须自己跟踪文件中的当前上下文。按照这些思路应该可以解决问题:

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

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