私は 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 以外の要素を含む行を削除します。
- 純粋な HTML で Document オブジェクトを作成する
- 変更を加える
- HTML に戻り、最初に削除した 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();
ヘルプやご意見をお寄せいただきありがとうございます。