新手问题 Ruby 分析 XML 文件中 each block 的问题

ask_acct · May 28, 2014 · Last by ask_acct replied at May 30, 2014 · 2272 hits

请问,分析一个 XML 文件 (参看底部),想汇总成文档成 1 Ruby The Ruby Way 2 Space The Case for Mars

appPathArray.each do |i|
  puts i
  doc.elements.each("library/section") { |e| puts e.attributes["name"] } 
  doc.elements.each("library/section") { |e| puts e.elements["title"].text }
end

问题是,上边代码第三四行,如何控制输出第 i 行?类似 doc.elements.each("library/section") { |e| puts e(i).attributes["name"] } 谢谢

The Ruby Way Hal Fulton Second edition. The book you are now reading. Ain't recursion grand? The Case for Mars Robert Zubrin Pushing toward a second home for the human race. First Man: The Life of Neil A. Armstrong James R. Hansen Definitive biography of the first man on the moon.

介绍个工具: Nokogiri

#1 楼 @hz_qiuyuanxin Nokogiri 堪称神器 - - 包括 pa 网站。哈哈哈

在命令行测试出的作法:

$ irb -rnokogiri
>> doc = Nokogiri::XML(open('./raw.xml'))
=> ...
>> doc.xpath('//section').each_with_index{|x,i| puts "#{i+1} #{x.attributes['name']} #{x.at('title').text}"}
1 Ruby The Ruby Way
2 Space The Case for Mars
=> ...

第三个没出来,改成这样子:

require "nokogiri"
doc = Nokogiri::XML(open('./raw.txt'))
index = 0
doc.xpath('//section').each do |section|
  name = section.attributes['name']
  section.search('title').each do |title|
    index+=1
    puts "#{index} #{name} #{title.text}"
  end
end

#4 楼 @rco 感谢,感谢,我后来用自带的 REXML 搞定了,以后还有这类的处理我会尝试使用 Nokogiri,再次感谢您的回复和例子。

也感谢楼上两位的回复,谢谢

You need to Sign in before reply, if you don't have an account, please Sign up first.