Это должно сработать. Он просто перебирает все узлы «product_category». Для каждого узла он получает идентификаторы предков, а затем печатает имена и идентификаторы.
doc = Nokogiri::XML(open('test.xml'))
doc.search('product_category').each do |node|
# get the current node's ID
id = node.attr('id')
# get all ancestor node IDs
ancestor_ids = node.ancestors('product_category').map { |anode| anode.attr('id') }
# put all the node IDs into an array
all_ids = ([id] + ancestor_ids).reverse
# output node name with all IDs and prepend spaces based on number of ancestors
puts "#{' ' * ancestor_ids.size}#{node.attr('name')}, [#{all_ids.join(', ')}]"
end
Вывод:
Computer, [409]
Server, [409, 414]
Multimedia Server, [409, 414, 511]
Server Equips, [409, 1645]
Computer Equips, [97]
Adaptor, [97, 127]
Audior, [97, 127, 133]
DVI, [97, 127, 128]
Firewire, [97, 127, 134]
Gender Changer, [97, 127, 135]
HDMI - DVI / DVI-I, [97, 127, 129]
HDMI, [97, 127, 137]
Keyboard, [97, 127, 139]
Mouse, [97, 127, 141]
Scart, [97, 127, 144]
Serial, [97, 127, 196]
SUN KVM, [97, 127, 198]
USB Adap, [97, 127, 147]
USB Adap, [97, 127, 147, 743]
USB Şarj Adap, [97, 127, 147, 1040]
USB C Adap, [97, 127, 147, 1088]
USB Seri Adap, [97, 127, 147, 1611]
USB Ethernet Adap, [97, 127, 147, 1612]