html - JSoup 在正文后添加 Wrapper div

标签 html html-parsing jsoup

我正在尝试添加 <div class="wrapper">到我在 body 标签后生成的 html。我想要结尾 </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 时才能得到它。

最佳答案

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

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

我们将使用 XMLTreeBuilder 的 Parser.xmlParser 作为解析器参数(否则它使用 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());

关于html - JSoup 在正文后添加 Wrapper div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734365/

相关文章:

java - android 通过Jsoup迭代HTML页面中的数据

html - R - 将唯一的 HTML/XML 消息解析为数据框

javascript - 纯 javascript 只切换一次使用 data-getAttribute 来比较

html - 如何在源不存在的情况下显示默认图像

html - Codepen 与 Bootstrap : CSS behaves differently

android - Jsoup select() 在 Android 应用程序中不返回任何内容

java - 如何从JSoup的DIV中获取图像

java - 给定 xPath,是否可以突出显示 JavaFX webView 中的元素?

android - 如何通过 jsoup 从以下 scipt 获取图像

html - 元素在媒体查询 : 380px - but not when resized from bigger width and down to 380px 中的位置很好