我有這樣的XML:引入nokogiri - tag.contents返回false數據
<record>
<f id="27">John Smith</f>
<f id="28"/>
</record>
我引入nokogiri解析這樣說:
# I get the record from the whole document
...
fields = record.xpath("f")
for field in fields
puts field.content
end
返回此:
John Smith
\n 28 \n
哪個不正確。第二個field
標籤在標籤內沒有任何內容,它應該返回一個空值。對?任何幫助?
順便說一句,同樣的事情發生在LibXML中。
編輯:
實際代碼:
xml = Nokogiri::XML("<?xml version="1.0" ?><records><record><f id="27">John Smith</f><f id="38"/></record></records>")
records = xml.xpath("//record")
records.map{|record|
fields = record.xpath("f")
fields.to_enum(:each_with_index).collect{|field,index|
[field.content, index]
}
}
奇怪,適合我(將xpath更改爲'// f')。向我們展示如何創建「記錄」。還要注意的是,在Ruby for-loops中是非常不習慣的(每次使用Enumerable#) – tokland
還有一個'records'變量,我從'records.each {| record | ...}'和'records'來自'SOMEXML.xpath(「// record」)'。我實際上使用.each,而不是for循環。 –
如果粘貼能夠重現問題的精確(但最短)的XML和代碼,會更容易。 – tokland