2017-06-01 8 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 
相关问题