如何使用Nokogiri删除重复的嵌套标签

问题描述 投票:2回答:2

我有带有嵌套重复标签的HTML:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div>
      <div>
        <div>
          <p>Some text</p>
        </div>  
      </div>
    </div>
  </body>
</html> 

我想删除没有任何属性的嵌套重复div。生成的HTML应该如下所示:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div>
      <p>Some text</p>
    </div>  
  </body>
</html> 

如何使用Nokogiri或纯Ruby来完成?

ruby nokogiri
2个回答
1
投票

通常,我不喜欢Nokogiri使用的可变结构,但是在这种情况下,我认为它对您有利。这样的事情可能会起作用:


0
投票

基于HTML的结构,这应该可以帮助您:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div>
      <div>
        <div>
          <p>Some text</p>
        </div>  
      </div>
    </div>
  </body>
</html> 
EOT

dd = doc.at('div div').parent
dp = dd.at('div p')
dd.children.unlink
dp.parent = dd
© www.soinside.com 2019 - 2024. All rights reserved.