2016-11-03 34 views
4

私は以下のサンプルコードを持っています。jsoupを使ってhtmlを解析する際に空白と改行を避ける

String sample = "<html> 
<head> 
</head> 
<body> 
This is a sample on    parsing html body using jsoup 
This is a sample on    parsing html body using jsoup 
</body> 
</html>"; 

Document doc = Jsoup.parse(sample); 
String output = doc.body().text(); 

私は

This is a sample on parsing html body using jsoup This is a sample on `parsing html body using jsoup` 

として出力を得るしかし、私はこの出力を得るように、それを解析するにはどうすればよい

This is a sample on    parsing html body using jsoup 
This is a sample on    parsing html body using jsoup 

として出力したいですか?あるいは、Javaでこれを行う別の方法がありますか?

答えて

3

ドキュメントのきれいな印刷を無効にして、必要な出力を得ることができます。しかし、.text().html()に変更する必要があります。

Document doc = Jsoup.parse(sample); 
doc.outputSettings(new Document.OutputSettings().prettyPrint(false)); 
String output = doc.body().html(); 
0

HTML仕様では、複数の空白文字を1つの空白にする必要があります。したがって、サンプルを解析するとき、パーサーは余分な空白文字を正しく除去します。

パーサの動作方法を変更することはできません。前処理ステップを追加して、複数の空白を破られないスペース( )に置き換えることができます。これは崩壊しません。しかし、副作用は、もちろん、それらが、壊れないものであることです(実際には、doc.body()。text()のようにレンダリングされたテキストを使用したい場合は関係ありません)。

関連する問題