Jon-Michael Deldin

BMX, bike trials, & software from the Pacific Northwest

Counting the number of XML elements with REXML and XPATH

Sometimes you need a quick-and-dirty way of counting some elements, but not as dirty as calling out to shell and using grep and wc on it (e.g., grep '<resident>' my.xml | wc -l). Imagine you have the only have the Ruby standard library available and wish to count the number of <resident> elements:

require "rexml/document"

xml = <<EOF
<?xml version="1.0" encoding="utf-8"?>
  <resident name="Foo"/>
  <resident name="Bar"/>
  <resident name="Baz"/>

doc =
REXML::XPath.first(doc, "count(//residents/resident)")
#=> 3