LoginSignup
2
3

More than 5 years have passed since last update.

RubyのNokogiriでXMLをパースする

Last updated at Posted at 2018-02-13

サンプル

require 'nokogiri'

count = 0
File.open("./source.xml", 'r') do |f|
  xml = Nokogiri::XML(f)
  item_nodes = xml.xpath('/xpath/to/contents')
  item_nodes.each do |elem|
    count += 1
  end
end

puts count #=> ex. 100
  • Nokogiri::XMLにFileクラスのオブジェクトを渡す。
  • 要素の探索はXPathを使う
  • xpathメソッドの返り値はNokogiri::XML::NodeSetのオブジェクトで、Enumerable

XPathの指定方法は
https://qiita.com/rllllho/items/cb1187cec0fb17fc650a
を参考にしました。

以上です。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3