2017-06-01 115 views
0

我有一個來自API的HTML,它是我想要清理和格式化的。解析一個嵌套標籤,將它移動到父級以外,並使用Nokogiri更改其類型

我試圖得到任何<strong>標籤是一個<p>標籤中的第一個元素,並將其更改爲是<p>標籤的父,和<p>標籤轉換爲<h4>

例如:

<p><strong>This is what I want to pull out to an h4 tag.</strong>Here's the rest of the paragraph.</p> 

變爲:

<h4>This is what I want to pull out to an h4 tag.</h4><p>Here's the rest of the paragraph.</p> 

編輯:道歉的問題過於 '請寫出這對我來說' 的性質。我發佈了我在下面提出的解決方案。我只是花時間去真正瞭解Nokogiri的工作原理,但它非常強大,看起來你幾乎可以做任何事情。

+0

請編輯您的問題,包括您迄今爲止編寫的代碼,以及您正在使用的輸入和期望輸出的示例。 –

+0

編輯添加示例。 – gregblass

+2

是的,這是可能的。請編輯您的問題以描述您到目前爲止所嘗試的內容。 –

回答

0
doc = Nokogiri::HTML::DocumentFragment.parse(html) 

doc.css("p").map do |paragraph| 
    first = paragraph.children.first 
    if first.element? and first.name == "strong" 
    first.name = 'h4' 
    paragraph.add_previous_sibling(first) 
    end 
end 
相關問題