counting elements in xml with Nokogiri

ruby

Solution

You get `5` as the result because there are five child nodes under the root `<element>` node. There are two `<name>` nodes and three text nodes that each consist of whitespace; one between the opening `<element>` and the first `<name>`, one between the two `<names>`, and one between the second `<name>` and the closing `</element>`:

doc.root.children.each do |c|
  p c
end

output:

#<Nokogiri::XML::Text:0x80544a04 "\n  ">
#<Nokogiri::XML::Element:0x80544900 name="name" children=[#<Nokogiri::XML::Text:0x8054470c "Married with Children">]>
#<Nokogiri::XML::Text:0x80544554 "\n  ">
#<Nokogiri::XML::Element:0x80544478 name="name" children=[#<Nokogiri::XML::Text:0x80544284 "Married with Children">]>
#<Nokogiri::XML::Text:0x805440cc "\n">

If you use the `noblanks` option when parsing Nokogiri won’t include these whitespace nodes:

doc = Nokogiri::XML(open('link..to....element.xml')) { |c| c.noblanks }

Now `doc.root.children.count` will equal `2`, only the two `<name>` element nodes will be included.

Problem

I'd like to understand why `count` gives me `5`? If I'm at the root element and I want to know my children, it is supposed to give me `2`. ``` doc = Nokogiri::XML(open('link..to....element.xml')) root = doc.root.children.count puts root <element> <name>Married with Children</name> <name>Married with Children</name> </element> ```

Original source