【问题标题】:Nokogiri and finding element by nameNokogiri 和按名称查找元素
【发布时间】:2011-08-15 01:43:21
【问题描述】:

我正在使用 Nokogiri 和以下 sn-p 解析 XML 文件:

doc.xpath('//root').each do |root|
  puts "# ROOT found"
  root.xpath('//page').each do |page|
    puts "## PAGE found / #{page['id']} / #{page['name']} / #{page['width']} / #{page['height']}"
    page.children.each do |content|
      ...
    end
  end
end

如何解析页面元素中的所有元素?共有三种不同的元素:图像、文本和视频。如何为每个元素做一个案例陈述?

【问题讨论】:

    标签: ruby xml nokogiri xml-parsing


    【解决方案1】:

    老实说,你看起来很接近我..

    doc.xpath('//root').each do |root|
      puts "# ROOT found"
      root.xpath('//page').each do |page|
        puts "## PAGE found / #{page['id']} / #{page['name']} / #{page['width']} / #{page['height']}"
        page.children.each do |child|
          case child.name
           when 'image'  
              do_image_stuff
           when 'text'
              do_text_stuff
           when 'video'
              do_video_stuff
           end
        end
      end
    end
    

    【讨论】:

    • 谢谢。实际上自己使用matches解决了它?(选择器)方法:)
    【解决方案2】:

    Nokogiri 的 CSS 和 XPath 访问器都允许指定多个标签,这对于这类问题很有用。而不是遍历文档的page 标签中的每个标签:

    require 'nokogiri'
    
    doc = Nokogiri::XML('
      <xml>
      <body>
      <image>image</image>
      <text>text</text>
      <video>video</video>
      <other>other</other>
      <image>image</image>
      <text>text</text>
      <video>video</video>
      <other>other</other>
      </body>
      </xml>')
    

    这是使用 CSS 进行的搜索:

    doc.search('image, text, video').each do |node|
      case node.name
      when 'image'
        puts node.text
      when 'text'
        puts node.text
      when 'video'
        puts node.text
      else
        puts 'should never get here'
      end
    end
    
    # >> image
    # >> image
    # >> text
    # >> text
    # >> video
    # >> video
    

    请注意,它按照 CSS 访问器指定的顺序返回标签。如果需要文档中标签的顺序,可以使用XPath:

    doc.search('//image | //text | //video').each do |node|
      puts node.text
    end
    
    # >> image
    # >> text
    # >> video
    # >> image
    # >> text
    # >> video
    

    在任何一种情况下,程序都应该运行得更快,因为所有搜索都发生在 libXML 中,只返回 Ruby 处理所需的节点。

    如果您需要将搜索限制在 &lt;page&gt; 标记内,您可以预先搜索以找到 page 节点,然后在其下方搜索:

    doc.at('page').search('image, text, video').each do |node|
      ...
    end
    

    doc.at('//page').search('//image | //text | //video').each do |node|
      ...
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2014-09-19
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多