更新时间: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
search
和at
是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.
name
和text
也是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.