小编DNa*_*del的帖子

使用Ruby和Nokogiri解析大型XML文件

我有一个大的XML文件(大约10K行)我需要定期解析这种格式:

<summarysection>
    <totalcount>10000</totalcount>
</summarysection>
<items>
     <item>
         <cat>Category</cat>
         <name>Name 1</name>
         <value>Val 1</value>
     </item>
     ...... 10,000 more times
</items>
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用nokogiri解析每个节点,以计算一个类别中的项目数量.然后,我想从total_count中减去该数字,得到一个读数为"Count of Interest_Category:n,Count of All Else:z"的输出.

这是我现在的代码:

#!/usr/bin/ruby

require 'rubygems'
require 'nokogiri'
require 'open-uri'

icount = 0 
xmlfeed = Nokogiri::XML(open("/path/to/file/all.xml"))
all_items = xmlfeed.xpath("//items")

  all_items.each do |adv|
            if (adv.children.filter("cat").first.child.inner_text.include? "partofcatname")
                icount = icount + 1
            end
  end

othercount = xmlfeed.xpath("//totalcount").inner_text.to_i - icount 

puts icount
puts othercount
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但速度很慢!对于10,000件物品,我说的时间超过10分钟.有一个更好的方法吗?我是以不太理想的方式做事吗?

ruby xml nokogiri

8
推荐指数
2
解决办法
1万
查看次数

使用Ruby中的Mechanize选择List

我正在尝试使用Mechanize with Ruby设置选择列表的值.我可以使用选择列表导航到页面,使用.form方法获取表单,然后找到选择列表.

report_form =page.form('form1')
pp report_form.field_with(:name => "report_type")
Run Code Online (Sandbox Code Playgroud)

正确返回正确的对象.

但是,我仍然无法设置此字段的值!我试过了:

report_form.field_with(:name => "report_type").options.first.select
report_form.field_with(:name => "report_type").options[1].select
report_form.field_with(:name => "report_type").value = "Foo"
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时:

pp report_form.field_with(:name => "report_type")
Run Code Online (Sandbox Code Playgroud)

值字段仍为空.

有什么我想念的吗?提示?窍门?比在http://mechanize.rubyforge.org上生活的更好的机械化文档?

谢谢!

编辑:相关的HTML是:相关的HTML是:

<TD>
<select id="report_type" name="report_type">
    <option value="Foo1">Opt 1</option>
    <option value="Foo2">Opt 2</option>
    <option value="Foo3">Opt 3</option>
</select></TD>
Run Code Online (Sandbox Code Playgroud)

ruby mechanize mechanize-ruby

5
推荐指数
1
解决办法
5631
查看次数

标签 统计

ruby ×2

mechanize ×1

mechanize-ruby ×1

nokogiri ×1

xml ×1