代码之家  ›  专栏  ›  技术社区  ›  Lucas P.

jsoup:是否将属于正文的文本换行到一个分区中?

  •  2
  • Lucas P.  · 技术社区  · 6 年前

    我有一个类似这样的HTML字符串:

    <body>
    I am a text that needs to be wrapped in a div!
    <div class=...>
      ...
    </div>
    ...
    I am more text that needs to be wrapped in a div!
    ...
    </body>
    

    所以我需要将悬空的HTML文本包装在它自己的分区中,或者将整个正文(文本和其他分区)包装在顶级分区中。有没有一种方法可以用JSoup来实现这一点?非常感谢!

    1 回复  |  直到 6 年前
        1
  •  1
  •   Luk    6 年前

    如果要将整个身体包裹在一个分区中,请尝试以下操作:

        Element body = doc.select("body").first();
        Element div = new Element("div");
        div.html(body.html());
        body.html(div.outerHtml());
    

    <body>
      <div>
        I am a text that needs to be wrapped in a div! 
       <div class="...">
         ... 
       </div> ... I am more text that needs to be wrapped in a div! ... 
      </div>
     </body>

    如果要将每个文本单独包装,请尝试以下操作:

        Element body = doc.select("body").first();
        Element newBody = new Element("body");
    
        for (Node n : body.childNodes()) {
            if (n instanceof Element && "div".equals(((Element) n).tagName())) {
                newBody.append(n.outerHtml());
            } else {
                Element div = new Element("div");
                div.html(n.outerHtml());
                newBody.append(div.outerHtml());
            }
        }
        body.replaceWith(newBody);
    

    <body>
      <div>
        I am a text that needs to be wrapped in a div! 
      </div>
      <div class="...">
        ... 
      </div>
      <div>
        ... I am more text that needs to be wrapped in a div! ... 
      </div>
     </body>