繁体   English   中英

如何使用JSoup仅删除两个不同标签之间的文本

[英]How to remove only text between two different Tags using JSoup

<div class="orcl6w2">
  <div class="orcl6w3">
    <table >
      <tbody>
        <tr>
          <td>
            <table>
              <tbody>
                <tr>
                  <td>
                    <center>
                      <strong>As Published In </strong>                                      
                    </center>
                  </td>
                </tr>
              </tbody>
            </table>
            <h2>DEVELOPER: PL/SQL Practices</h2>
            <hr />
            <strong>Steven Feuerstein </strong>This has to be deleted                                                        
            <em>Oracle PL/SQL Programming</em>This has to be deleted too.                                                             
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

在这里,我要删除hr标签之后的文本以及标签。

<hr />
<strong>Steven Feuerstein </strong>This has to be deleted                                                        
<em>Oracle PL/SQL Programming</em>This has to be deleted too.

我尝试使用以下代码删除。 但是只有下面的代码,我才能删除hr标签之后的标签。 但是我无法删除文本,即, This has to be deleted并且This has to be deleted too.

if (elements.select("hr").size() > 0) {
    final Element hrfound = elements.select("hr").last();
    final int hrIdx = hrfound.siblingIndex();

    for (Element e : hrfound.siblingElements()) {
        if (e.siblingIndex() > hrIdx) {
            e.remove();
        }
    }
} 

请帮忙....

您使用的方法( hrfound.siblingElements() )仅获取Element对象,但是您尝试删除的文本也属于Node类型。 我也不会尝试通过使用索引来删除它们。 相反,在找到hr元素之后,可以使用nextSibling()方法获取之后的同级; 它将选择Node类型,以便同时获取元素和文本节点。

下面的代码应该可以完成您想做的事情:

while(hrfound.nextSibling() != null) {
    hrfound.nextSibling().remove();
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM