我正在尝试添加 <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>
</head>
<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></head><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/