2011-05-05 7 views
0

다음 XML에서 "작성자"및 "사실"태그를 구문 분석하는 방법을 알 수 없습니다. 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을 사용하여 요소를 해쉬로 푸시했고, 분명히 여러 사실이 있습니다.

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

+0

괜찮습니다. 내 대답이 문제를 해결 한 경우 옆에있는 체크 표시를 클릭하여 문제를 "수락 됨"으로 표시 할 수 있습니다. – michaelmichael

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 

트릭은 네임 스페이스에 당신은 당신이 원하는대로 데이터 구조를 사용할 수 있지만이는 factauthor 태그의 내용을 가져옵니다.

+0

네임 스페이스는 위의 xml 조각에 표시되지 않지만 링크 된 문서의 소스 코드를 보시면 나타납니다. – hectorsq

+0

'author' 태그가 하나 뿐이므로'@ xml_doc.at' 및'nodes.inner_text '또는 단지'nodes.text'. –