O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#31 Counting Tags (xml_tag_counter.rb)

XML is strict about its internal structure. It can only have a single top-level element (called the root element), but that root element can have any number of elements within itself, and each of those elements can have any number of other elements within itself, continuing on recursively. We want a script that we can run on an XML file that will output how many times each tag (or element) occurs within that document, no matter how many layers deep it appears—for example, we want to find all <p> tags regardless of whether or not those tags are immediately within the top-level <html> element, or within some other element, such as a <blockquote> or <div>. Let’s take a look.

The Code

  #!/usr/bin/env ruby
  # xml_tag_counter.rb ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required