Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nokogiri children method

I have the following XML here:

<listing>
    <seller_info>
    <payment_types>Visa, Mastercard, , , , 0, Discover, American Express </payment_types>
    <shipping_info>siteonly, Buyer Pays Shipping Costs </shipping_info>
    <buyer_protection_info/>
    <auction_info>
    <bid_history>
    <item_info>
</listing>

The following code works fine for displaying first child of the first //listing node:

require 'nokogiri'
require 'open-uri' 

html_data = open('http://aiweb.cs.washington.edu/research/projects/xmltk/xmldata/data/auctions/321gone.xml')

nokogiri_object = Nokogiri::XML(html_data)
listing_elements = nokogiri_object.xpath("//listing")

puts listing_elements[0].children[1]

This also works:

puts listing_elements[0].children[3]

I tried to access the second node <payment_types> with the the following code:

puts listing_elements[0].children[2]

but a blank line was displayed. Looking through Firebug, it is clearly the 2nd child of the listing node. In general, only odd numbers work with the children method.

Is this a bug in Nokogiri? Any thoughts?

like image 613
Ben Avatar asked Aug 19 '26 05:08

Ben


1 Answers

It's not a bug, its the space created while parsing strings that contain "\n" (or empty nodes), but you could use the noblanks option to avoid them:

nokogiri_object = Nokogiri::XML(html_data) { |conf| conf.noblanks }

Use that and you will have no blanks in your array.

like image 72
Gerry Avatar answered Aug 22 '26 02:08

Gerry