2010-12-03 29 views
0

現在,這是我的html:如何使用nokogiri在文本中嵌入元素?

<div class="cardtextbox"><i>(<img src="/Handlers/Image.ashx?size=small&amp;name=BR&amp;type=symbol" alt="Black or Red" align="absbottom" /> can be paid with either <img src="/Handlers/Image.ashx?size=small&amp;name=B&amp;type=symbol" alt="Black" align="absbottom" /> or <img src="/Handlers/Image.ashx?size=small&amp;name=R&amp;type=symbol" alt="Red" align="absbottom" />.)</i></div><div class="cardtextbox"><img src="/Handlers/Image.ashx?size=small&amp;name=3&amp;type=symbol" alt="3" align="absbottom" /><img src="/Handlers/Image.ashx?size=small&amp;name=B&amp;type=symbol" alt="Black" align="absbottom" />, Discard a card: Target creature gets -2/-2 until end of turn.</div><div class="cardtextbox"><img src="/Handlers/Image.ashx?size=small&amp;name=3&amp;type=symbol" alt="3" align="absbottom" /><img src="/Handlers/Image.ashx?size=small&amp;name=R&amp;type=symbol" alt="Red" align="absbottom" />: Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step.</div></div> 

而我想獲得:從紅色=> R

[ 
["(B/R can be paid with either B or R.)"], 
["3 B, Discard a card", "Target creature gets -2/-2 until end of turn"], 
["3 R",     "Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step."] 
] 

映射經由colorhash完成。紅色來自img標記,alt屬性。

回答

0

我不確定colorhash是什麼,或者它與這個問題有什麼關係,但是這裏有些東西應該讓你接近。如果你真的想要一個嵌套的答案數組,你必須定義一個遞歸函數來處理一個節點,併爲自己判斷一個節點是不是葉。

require 'nokogiri' 
colorhash = { 
    'Red'   => 'R', 
    'Black'  => 'B', 
    'Black or Red' => 'B/R' 
} 

h = Nokogiri::HTML html_from_question 

# Replace all images with alt text, possibly transformed 
h.xpath('//img[@alt]').each{ |i| i.swap(colorhash[i['alt']] || i['alt']) } 

require 'pp' 
pp h.css('.cardtextbox').map(&:text) 

#=> ["(B/R can be paid with either B or R.)", 
#=> "3B, Discard a card: Target creature gets -2/-2 until end of turn.", 
#=> "3R: Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step."] 
相關問題