Nokogiri :: XML :: SAX :: Document有沒有類似(accessions = doc.at_xpath('//Node/Childtag').content)
的方法?使用Nokogiri SAX從節點中選擇兒童?
我喜歡XML:
<accession>Police-1234</accession>
<accession>Police-6574</accession>
<police>
<privateCar>
<fullName>BMW 750Li</fullName>
</privateCar>
<officeCar>
<fullName>Ford Mustang GT</fullName>
</officeCar>
<optional>
<fullName>Porsche carrera 511</fullName>
</optional>
</police>
我的代碼是一些什麼樣的:
require 'rubygems'
require 'nokogiri'
include Nokogiri
class PostCallbacks < XML::SAX::Document
def initialize
@in_title = false
@in_title2 = false
end
def start_element(element, attributes)
@attrs = attributes
@content = ''
@in_title = element.eql?("accession")
# Collecting all the other nodes/tags
@in_title2 = element.eql?("fullName")
end
def end_document
# puts "Here is where the attributes could be played with"
end
def characters string
string.strip!
if @in_title and !string.empty?
puts "Accession: #{string}"
elsif @in_title2 and !string.empty?
puts "Full Name: #{string}"
end
@content << string if @content
end
end
parser = XML::SAX::Parser.new(PostCallbacks.new)
parser.parse(File.open(ARGV[0]))
我的結果是:
Accessions:Police-1234
Accessions:Police-6574
Full Name: BMW 750Li
Full Name: Ford Mustang GT
Full Name: Porsche carrera 511
現在我有兩個問題。
- 如何限制收集值爲「Police-1234」的「加入」元素。
- 我想只檢索privatecar的孩子的全名。即我只想要BMW 750Li作爲我的結果。
對於第一點,我通常使用doc.xpath(//accession).first
來拉出XML中的第一個條目。
對於第二點,我知道我可以使用XPath與doc.at_xpath(//police/privateCar/fullName)
進行選擇,但SAX解析器有類似的地方嗎?
我正在使用SAX,因爲我有一個很大的XML文件需要解析。