2011-05-05 105 views
0

我無法弄清楚如何從以下XML中解析「author」和「fact」標籤。如果格式對XML文檔看起來奇怪here is a link使用Nokogiri解析XML

<response stat="ok"> 
−<ltml version="1.1"> 
    −<item id="5403381" type="work"> 
     <author id="21" authorcode="rowlingjk">J. K. Rowling</author> 
     <url>http://www.librarything.com/work/5403381</url> 
    −<commonknowledge> 
    −<fieldList> 
    −<field type="42" name="alternativetitles" displayName="Alternate titles"> 
    −<versionList> 
    −<version id="3413291" archived="0" lang="eng"> 
     <date timestamp="1298398701">Tue, 22 Feb 2011 13:18:21 -0500</date> 
     −<person id="18138"> 
      <name>ablachly</name> 
      <url>http://www.librarything.com/profile/ablachly</url> 
      </person> 
     −<factList> 
       <fact>Harry Potter and the Sorcerer's Stone </fact> 
      </factList> 
       </version> 
     </versionList> 
     </field> 

到目前爲止,我已經試過這個代碼來獲取作者,但它不工作:

@xml_doc = Nokogiri::XML(open("http://www.librarything.com/services/rest/1.1/?method=librarything.ck.getwork&isbn=0590353403&apikey=d231aa37c9b4f5d304a60a3d0ad1dad4")) 

@xml_doc.xpath('//response').each do |n| 
    @author = n  
end 

回答

1

我不能使用你提供的鏈接在任何節點得到深度超過//response。我最終使用了Nokogiri::XML::Reader並將元素推送到散列表中,因爲可能有多個作者,並且肯定存在多個事實。你可以使用任何你喜歡的數據結構,但是這得到factauthor標籤的內容:

require 'nokogiri' 
require 'open-uri' 

url = "http://www.librarything.com/services/rest/1.1/?method=librarything.ck.getwork&isbn=0590353403&apikey=d231aa37c9b4f5d304a60a3d0ad1dad4" 
reader = Nokogiri::XML::Reader(open(url)) 

book = { 
    author: [] 
    fact: [] 
} 

reader.each do |node| 
    book.each do |k,v| 
    if node.name == k.to_s && !node.inner_xml.empty? 
     book[k] << node.inner_xml 
    end 
    end 
end 
+0

謝謝邁克爾,工作很好 – Bryan 2011-05-06 17:23:31

+0

沒問題!如果我的答案解決了您的問題,您可以點擊旁邊的複選標記將其標記爲「已接受」。 – michaelmichael 2011-05-06 18:09:51

1

你可以嘗試:

nodes = @xml_doc.xpath("//xmlns:author", "xmlns" => "http://www.librarything.com/") 
puts nodes[0].inner_text 

nodes = @xml_doc.xpath("//xmlns:fact", "xmlns" => "http://www.librarything.com/") 
nodes.each do |n| 
    puts n.inner_text 
end 

的訣竅是在命名空間。

+0

上面的xml片段中沒有顯示命名空間,但是如果您查看鏈接文檔的源代碼,則會顯示 – hectorsq 2011-05-11 23:34:43

+0

因爲只有一個'author'標籤,所以使用'@ xml_doc.at'和'nodes.inner_text更簡單'或只是'nodes.text'。 – 2011-05-15 23:10:17