且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Ruby和Nokogiri将XML节点解析为CSV

更新时间:1970-01-01 07:58:00

这假定每个Offer元素始终具有相同的子节点(尽管它们可以为空):

This assumes that each Offer element always has the same child nodes (though they can be empty):

CSV.open('output.csv', 'wb') do |csv|
  doc.search('Offer').each do |x|
    csv << x.search('*').map(&:text)
  end
end

并获取标头(从第一个Offer元素开始):

And to get headers (from the first Offer element):

CSV.open('output.csv', 'wb') do |csv|
  csv << doc.at('Offer').search('*').map(&:name)
  doc.search('Offer').each do |x|
    csv << x.search('*').map(&:text)
  end
end

searchat是Nokogiri函数,可以采用XPath或CSS选择器字符串. at将返回元素的第一次出现; search将提供匹配元素的数组(如果找不到匹配项,则为空数组).在这种情况下,*将选择作为当前节点的直接子代的所有节点.

search and at are Nokogiri functions that can take either XPath or CSS selector strings. at will return the first occurrence of an element; search will provide an array of matching elements (or an empty array if no matches are found). The * in this case will select all nodes that are direct children of the current node.

nametext也是Nokogiri函数(用于元素). name提供元素的名称; text提供节点的文本或CDATA内容.

Both name and text are also Nokogiri functions (for an element). name provides the element's name; text provides the text or CDATA content of a node.