這兩項工作:
require 'nokogiri'
doc = Nokogiri::XML(xml)
doc.search('//div[@id]/text()').select{ |n| n.text['Total'] }.first.text.split.last
和
doc.search('//div/text()').select{ |n| n.text['Total'] }.first.text.split.last
區別在於第一個應該運行得更快一點if你知道你正在尋找的div始終有一個id
。
如果ID始終以「showTotalSubIndex」開始,你可以使用:
doc.at('//div[starts-with(@id,"showTotalSubIndex")]').first.text.split.last
,如果你知道,只有將是一個文檔中,你可以使用:
doc.at('//div[starts-with(@id,"showTotalSubIndex")]').text.split.last
編輯:
Ryan認爲XML結構可能是一致的。如果是這樣的:
doc.at('//div[2]').text[/(\$\d+)/, 1]
:-)