一、Jsoup是什么?
Jsoup是Java HTML解析器:jsoup是用于处理实际HTML的Java库。它提供了使用DOM,CSS和类似jquery的最好方法提取和处理数据的非常方便的API。
二、什么时候使用?
当需要解析html的时候使用,以我项目中的使用举个例子:
页面是一个富文本框展示的内容,然后把这部分内容存到数据库的时候存的是html标签,然后在页面点击下载的时候,是从数据库中读取到html标签,然后解析在转换成docx文档,部分代码:
html:是从数据库中读取到的html标签
for循环中是为了替换html标签中的图片,将图片转换成了base64格式,这样在不联网的情况下也能让图片正常显示 (图片是在ftp服务器上存放的)
public static String doTranslate(String html){
Document doc = Jsoup.parse(html, "utf-8");
//获取html中的img标签
Elements imgs = doc.body().getElementsByTag("img");
String src = null;
String fileId = null;
for(Element img : imgs) {
src = img.attr("src");
//获取对应的fileId
fileId = src.substring(src.indexOf("fileId=")+7);
img.attr("src",transImageToBase64(fileId));
}
return doc.html();
}
以上是jsuop解析html标签转换为doc文档的部分
----------------------------------------------------------------------------------
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws Exception {
if (!getLicense()) {
return;
}
String content = FileUtils.readFileToString(new File("F:/test.html"));
Document document = new Document();
DocumentBuilder build = new DocumentBuilder(document);
build.insertHtml(content);
document.save("F:/a.docx");
}
由于项目不能随意公布,以上代码就是一个生成docx的例子,具体项目中是生成到某个目录下 然后在用response写出去即可,这样的代码网上搜一下满地都是,可以参考一下