2010-09-02 44 views
3

我正在使用API​​,並且想知道如何根據標籤輕鬆搜索和顯示/格式化輸出。如何使用Ruby輕鬆解析XML以查詢和查找某些標記值?

例如,下面是使用API​​和XML輸出的示例頁面:

http://developer.linkedin.com/docs/DOC-1191

我希望能夠將每個記錄作爲一個對象,如User.first名User.last-name,以便我可以顯示和存儲信息,並進行搜索。

有沒有可能讓這更容易做的寶石?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<people-search> 
    <people total="108" count="10" start="0"> 
    <person> 
     <id>tePXJ3SX1o</id> 
     <first-name>Bill</first-name> 
     <last-name>Doe</last-name> 
     <headline>Marketing Professional and Matchmaker</headline> 
     <picture-url>http://media.linkedin.com:/....</picture-url> 
    </person> 
    <person> 
     <id>pcfBxmL_Vv</id> 
     <first-name>Ed</first-name> 
     <last-name>Harris</last-name> 
     <headline>Chief Executive Officer</headline> 
    </person> 
    ... 
    </people> 
    <num-results>108</num-results> 
</people-search> 

回答

4

這可能會嚇你一跳開始:

 
#!/usr/bin/env ruby 

require 'nokogiri' 

XML = %{<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<people-search> 
    <people total="108" count="10" start="0"> 
    <person> 
     <id>tePXJ3SX1o</id> 
     <first-name>Bill</first-name> 
     <last-name>Doe</last-name> 
     <headline>Marketing Professional and Matchmaker</headline> 
     <picture-url>http://media.linkedin.com:/foo.png</picture-url> 
    </person> 
    <person> 
     <id>pcfBxmL_Vv</id> 
     <first-name>Ed</first-name> 
     <last-name>Harris</last-name> 
     <headline>Chief Executive Officer</headline> 
    </person> 
    </people> 
    <num-results>108</num-results> 
</people-search>} 

doc = Nokogiri::XML(XML) 

doc.search('//person').each do |person| 
    firstname = person.at('first-name').text 
    puts "firstname: #{firstname}" 
end 
# >> firstname: Bill 
# >> firstname: Ed 

的想法是你遍歷一個重複的部分, 「人」,在這種情況下。然後,你挑出你想要的部分並提取文本。我正在使用Nokogiri的.at()來獲得第一次出現,但還有其他方法可以做到這一點。

Nokogiri網站有很好的例子和良好的書面文件,所以一定要花一點時間去理解它。你應該發現它很容易。

0

http://nokogiri.org/是您應該調查

+0

是的,我對Nokogiri很熟悉,但好像我不能指定標籤,它「循環」,我不得不數數......所以它不像一個對象......我誤解了那? – Angela 2010-09-02 05:14:07

+0

瞭解XPath。這是非常強大的,你應該能夠拿出你想要的東西。 – AboutRuby 2010-09-02 05:46:30

1

nokogiri是Ruby一個非常好的XML解析器,允許您使用XPath或CSS3選擇器來訪問你的XML選項,但它不是一個XML到對象映射

有一個名爲xml-mapping的項目,通過定義應映射到對象屬性的xpath表達式來執行此操作,反之亦然。

+0

嗯...我不知道nokogiri會工作嗎,你能給我一個例子使用類型的xml,linkedin輸出? – Angela 2010-09-02 05:15:59

1

This is how我使用內置的REXML來完成Ruby挑戰。

這是basicaly整個文檔的解析代碼:

doc = REXML::Document.new File.new cia_file 
doc.elements.each('cia/continent') { |e| @continents.push Continent.new(e) } 
doc.elements.each('cia/country') { |e| @countries.push Country.new(self, e) }