2011-09-18 19 views
0

我一直在試圖找到如何進行具體的足夠的例子。我正在使用Builder創建xml文件以用於導出/導入用途。我從應用程序導出此文件,並在導入時我想基於此xml文件創建新的記錄到數據庫。模型之間的關係完好無損。試圖解析可能非常深的嵌套xml文件與Nokogiri

我有幾個問題的類別,每個問題有幾個答案,可能會觸發一個或多個更多的問題。

我做了我的XML文件的簡化版本:https://gist.github.com/1225431

由於我由我自己做,我也願意聽取建議,如果我要準備不同的是xml文件。

questions = doc.css('questions') 

這就是我現在所處的位置,所以一開始就如此。我發現的所有例子都是針對完全不同類型的問題(或者我覺得)。

我是否甚至使用正確的工具來完成這項工作?任何幫助讚賞。

回答

1

Nokogiri是一個很棒的Ruby/XML解析庫,所以你絕對使用正確的工具來完成這項工作。由於您正在解析XML文檔,因此您應該使用XPath而不是CSS選擇器。幸運的是,Nokogiri has you covered

Nokogiri文檔有幾個basic, helpful usage tutorialsThis one回答你的問題。

以下是針對您的問題的代碼示例。希望這足以讓你開始:

require 'nokogiri' 

# Reads the `example.xml` file from the current directory. 
file = File.read("example.xml") 

# Uses Nokogiri::XML to parse the file. 
doc  = Nokogiri::XML(file) 

# Iterate over each <question> element and print 
# the text inside the first <name> element of each. 
doc.xpath("//question").each do |q| 
    puts q.at("name").text 

    # Iterate over each <selection> element within the 
    # current question and print its <name> and <conditional> 
    # line "name: conditional" 
    q.xpath("./selection").each do |selection| 
     puts "#{selection.at("name").text}: #{selection.at("conditional").text}" 
    end 

    # Same as above, but use variables. 
    q.xpath("./selection").each do |selection| 
     name    = selection.at("name").text 
     conditional = selection.at("conditional").text 

     puts "#{name}: #{conditional}" 
    end 
end 
+0

謝謝你的回覆。我嘗試了xpath和css,但總是被卡住了。我最終通過這種方式克服了這個問題。我爲每種類型,問題和選擇製作了自己的節點集。然後通過它們循環,讓它們進入數據庫。不漂亮,但至少它可以工作。 – thepanu

+0

我閱讀並閱讀了nokogiri.org上的教程,但無法圍繞它進行思考。 – thepanu

+0

雖然有一個問題。這個'doc.xpath(「// question」)'是否也會選擇內部選擇的問題作爲條件問題?那是我的頭痛。 – thepanu