[英]Preserve non-HTML elements with jsoup parse
我是jsoup的新手,使用非HTML元素(脚本)时遇到一些困难。 我有以下HTML:
<$if not dcSnippet$>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="generator" content="Outside In HTML Converter version 8.4.0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<$endif$>
<div style="position:relative">
<p style="text-align: left; font-family: times; font-size: 10pt; font-weight: normal; font-style: normal; text-decoration: none"><span style="font-weight: normal; font-style: normal">This is a test document.</span></p>
</div>
<$if not dcSnippet$>
</body>
</html>
<$endif$>
用于显示此内容的应用程序知道如何处理这些<if dcSnippet $>等语句。 因此,当我简单地用jsoup解析文本时,<和>被编码并且html被重新组织,因此它不能正确执行或显示。 像这样:
<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><$if not dcSnippet$>
<meta http-equiv="generator" content="Outside In HTML Converter version 8.4.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<$endif$>
<div style="position:relative">
<p style="text-align: left; font-family: times; font-size: 10pt; font-weight: normal; font-style: normal; text-decoration: none"><span style="font-weight: normal; font-style: normal">This is a test document.</span></p>
</div>
<$if not dcSnippet$>
<$endif$>
</body></html>
我的最终目标是要添加一些CSS和js包含项,并修改几个元素属性。 那不是真正的问题,我已经做了很多工作。 问题是我不知道如何保存非HTML元素并将格式设置在与原始格式相同的位置。 到目前为止,我的解决方案是这样的:
只要非HTML的位置是可以预测的,就目前而言,这是可行的。 但是我想知道是否有更好的方法可以做到这一点,因此我不必先“清理” HTML,然后手动重新介绍后来删除的内容。 这是我的代码的要点(希望我没有错过太多的声明):
String newLine();
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
while ((thisLine = br.readLine()) != null) {
if (thisLine.matches(".*<\\$if.*\\$>")) {
ifStatement = thisLine + "\n";
} else if (thisLine.matches(".*<\\$endif\\$>")) {
endifStatement = thisLine + "\n";
} else {
tempHtml += thisLine + "\n";
}
}
br.close();
Document doc = Jsoup.parse(tempHtml, "UTF-8");
doc.outputSettings().prettyPrint(false).escapeMode(EscapeMode.extended);
Element head = doc.head();
Element body = doc.body();
Element firstDiv = body.select("div").first();
[... perform my element and attribute inserts ...]
body.prependText("\n" + endifStatement);
body.appendText("\n" + ifStatement);
String fullHtml = (ifStatement + doc.toString().replaceAll("\\<", "<").replaceAll("\\>", ">") + "\n" + endifStatement);
BufferedWriter htmlWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
htmlWriter.write(fullHtml);
htmlWriter.flush();
htmlWriter.close();
非常感谢您的帮助或输入!
问题是我不知道如何保存非HTML元素并将格式设置在与原始格式相同的位置。
Jsoup是HTML解析器。 您提供的“ HTML文件”不包含HTML。 它更多是用类似HTML的语言编写的模板文件。
因此,Jsoup最多会将此模板文件视为无效的HTML文件。 这就是为什么所有非HTML元素都被转义的原因。
为了实现所需的功能,您必须编写自定义模板解析器。 Jsoup确实提供了一些通用类,这些类使此任务非常容易。
但是,根据设计,这些通用类仅保留供内部使用。
这给了我们四个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.