2009-05-19 15 views
2

你好,我正在使用LibXML來解析一個rss提要,我想知道是否有可能使用點語法訪問內容(或者一樣簡單)。是否可以使用點語法訪問xml對象的內容?

所以,如果我有:

<post> 
    <created_at>Sat Aug 09 05:38:12 +0000 2008</created_at> 
    <id>882281424</id> 
    <text>I so just thought the guy lighting the Olympic torch was falling when he began to run on the wall. Wow that would have been catastrophic.</text> 
    <source>web</source> 
    <truncated>false</truncated> 
    <in_reply_to_status_id></in_reply_to_status_id> 
    <in_reply_to_user_id></in_reply_to_user_id> 
</post> 

我能訪問它像

text = post.text 

回答

3

號最簡單的方法是使用XPath。例如,爲了讓所有的list「文本」節點是一個「後」節點的孩子:

doc = parser.parse 
text_node = doc.find('/post/text') #returns all children 

或獲得第一個(本例中只有)這樣的節點:

doc = parser.parse 
text_node = doc.find_first('/post/text') #returns first child only 
1

如果您準備好做一些設置工作,那麼您可能會發現HappyMapper有用。

你聲明一個類和它的映射(或者你感興趣至少部分) - 在你的情況下,它可能會是這個樣子

class Post 
    include HappyMapper 
    element :text, String 
end 

,並使用它是這樣的:

posts = Post.parse(File.read(path_to_rss.xml)) 
posts.each do |post| 
    puts post.text 
end 

所有經過充分測試,恐怕......

+0

測試這和它工作正常(與固定錯字)。如果XML僅包含' ...',則不需要遍歷它,只要執行`puts posts.text` – dbr 2009-07-30 07:50:13

相關問題