如何在 Java 中将 HTML 转换为文本

这个简单的主题是关于如何HTML 转换为 Java 中的文本。在 Windows、Linux 或 macOS 平台下运行的 *Java HTML 到纯文本 * 转换应用程序可以使用简单易用的 API 接口进行开发。

在 Java 中将 HTML 转换为文本的步骤

  1. 配置您的项目以从 Maven 存储库添加 Aspose.HTML for Java
  2. 在您的应用程序中包含对 Aspose.HTML 命名空间的引用
  3. 使用 String 对象读取源 HMTL 文件内容
  4. 初始化 HTMLDocument class 对象以加载源 HTML 字符串
  5. 初始化 INodeIterator 类对象以迭代节点并附加到 StringBuilder
  6. 将提取的 HTML 文本保存在磁盘上

为了从基于 HTML Java 的应用程序中提取文本,可以使用几行代码。我们将通过将源 HTML 加载到 String 对象并随后使用 HTMLDocument 类 加载该 String 来启动该过程。然后,我们将使用 INodeIterator 来提取、遍历 HMTL 节点并将其附加到 StringBuilder。最后,StringBuilder 将作为纯文本文件保存在磁盘上。

在 Java 中将 HTML 转换为文本的代码

import com.aspose.html.HTMLDocument;
import com.aspose.html.License;
import com.aspose.html.dom.Node;
import com.aspose.html.dom.traversal.INodeIterator;
import com.aspose.html.dom.traversal.filters.NodeFilter;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class HtmlToTextCoverter {
public static void main(String[] argsHTMLFile) throws Exception {
// Setting Aspose.Html Java API license to use complete features
License lic = new License();
lic.setLicense("HTML.Total.Java.lic");
// Read the HTML file in String
String content = null;
try {
content = readFileContent("TestFile.html", StandardCharsets.UTF_8);
} catch (IOException exception) {
exception.printStackTrace();
return;
}
// Instantiate HtmlDocument object to load HTML content in String
HTMLDocument document = new HTMLDocument(content, "");
// Initialize INodeIterator instance iterate HTML nodes
INodeIterator iterator = document.createNodeIterator(document, NodeFilter.SHOW_TEXT, new StyleFilter());
StringBuilder Stringbld = new StringBuilder();
// Temp Node object
Node node;
// Iterate through Nodes
while ((node = iterator.nextNode()) != null)
Stringbld.append(node.getNodeValue());
System.out.println(Stringbld.toString());
Files.write(Paths.get("HtmlToText_Java.txt"), Stringbld.toString().getBytes());
}
public static String readFileContent(String filePath, Charset encoding) throws IOException {
String fileContent = Files.lines(Paths.get(filePath), encoding)
.collect(Collectors.joining(System.lineSeparator()));
return fileContent;
}
}
class StyleFilter extends NodeFilter {
@Override
public short acceptNode(Node node) {
// In order to skip an element while fetching nodes, mention the name of element in upper case letters
return (node.getParentElement().getTagName() == "STYLE" || node.getParentElement().getTagName() == "SCRIPT"
? FILTER_REJECT : FILTER_ACCEPT);
}
}

上面 Java 中的示例在几个 API 调用中将 HTML 转换为纯文本。我们创建了 StyleFilter 类,它扩展了 NodeFilter 类,并实现了 AcceptNode 方法来设置客户节点过滤器并在转换过程中从 HTML 中省略不需要的节点。

在本主题中,我们探讨了如何在 Java 中从 HTML 中提取文本。如果您对将 MD 文件转换为 XPS 格式感兴趣,请继续主题如何使用 Java 将 Markdown 转换为 XPS

 简体中文