解析嵌套标记,将其移出父项,并使用Nokogiri更改其类型

时间:2017-06-01 19:05:58

标签: ruby nokogiri

我有来自API的HTML,我想清理并格式化它。

我尝试获取<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>

编辑:对于问题的性质表示道歉......请为我写这个&#39;。我发布了我在下面提出的解决方案。我只是花时间真正了解Nokogiri的工作方式,但它非常强大,而且看起来你几乎可以做任何事情。

1 个答案:

答案 0 :(得分: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