【问题标题】:JSoup Add Wrapper div after bodyJSoup 在正文后添加 Wrapper div
【发布时间】:2015-02-28 07:47:49
【问题描述】:

我正在尝试将<div class="wrapper"> 添加到我生成的 html 之后的 body 标记。我希望结尾 </div> 在结尾 </body> 之前。到目前为止我有

private String addWrapper(String html) {
    Document doc = Jsoup.parse(html);
    Element e = doc.select("body").first().appendElement("div");
    e.attr("class", "wrapper");

    return doc.toString();
}

我得到了

 </head>
  <body>
   &lt;/head&gt;  
  <p>Heyo</p>   
  <div class="wrapper"></div>
 </body>
</html>

我也无法弄清楚为什么我在 html 中也出现了“”。我只有在使用 JSoup 时才能得到它。

【问题讨论】:

    标签: html html-parsing jsoup


    【解决方案1】:

    Jsoup Document 使用 normalize 方法对文本进行规范化。 The method is here in Document class. 所以它用和标签包装。

    在Jsoup.parse()方法中可以带三个参数,parse(String html, String baseUri, Parser parser);

    我们将解析器参数作为 Parser.xmlParser 使用 XMLTreeBuilder (否则它使用 HtmlTreeBuilder 并规范化 html。)。

    我试过了,最新的代码(可能是优化的):

      String html = "<body>&lt;/head&gt;<p>Heyo</p></body>";
    
      Document doc = Jsoup.parse(html, "", Parser.xmlParser());
    
      Attributes attributes = new Attributes();
      attributes.put("class","wrapper");
    
      Element e = new Element(Tag.valueOf("div"), "", attributes);
      e.html(doc.select("body").html());
    
      doc.select("body").html(e.toString());
    
      System.out.println(doc.toString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 2011-08-10
      相关资源
      最近更新 更多