【问题标题】:How to replace some tags and remove others with line break in j2ee如何在 j2ee 中用换行符替换一些标签并删除其他标签
【发布时间】:2014-09-05 22:01:36
【问题描述】:

主要问题是获取 html 文件的内容并删除所有标签。
我以前读过这些问题:

1,2,3

在阅读完所有这些后,我决定使用jsoup,它确实对我有帮助。我还意识到如何保留换行符并将<p>标签替换为换行符。
现在我的问题是我有一个 html 文件,其中有一个 <H1> 标记,其中整个内容的标题都可用,我想用换行符保留它,但是使用 jsoup,第一个段落正好在标题之后,没有任何行休息。有人可以帮我吗?
我的 html 代码:

<DIV class="story-headline">
<H1 class="story-title">NFL 2014 predictions</H1>
</DIV>
<H3 class="story-deck">Our picks for playoff teams, surprises, Super Bowl</H3>
<P class="small lighttext">
<SPAN class="delimited">Posted: Sep 02, 2014 1:30 PM ET</SPAN>
<SPAN>Last Updated: Sep 04, 2014 10:27 AM ET</SPAN>
</P>

输出是:

NFL 2014 predictionsOur picks for playoff teams, surprises, Super Bowl

Posted: Sep 02, 2014 1:30 PM ETLast Updated: Sep 04, 2014 10:27 AM ET  

我希望它是:

NFL 2014 predictions  
Our picks for playoff teams, surprises, Super Bowl  
Posted: Sep 02, 2014 1:30 PM ET  
Last Updated: Sep 04, 2014 10:27 AM ET 

【问题讨论】:

  • 关闭你的
    后添加
  • HTML 代码是我的输入,我应该如何更改它?

标签: jakarta-ee jsoup


【解决方案1】:

你应该钩住目标DocumentOutputSettings,所以试试下面的方法:

public class HtmlWithLineBreaks 
{

  public String getCleanHtml(Document document)
  {
    document.outputSettings(new Document.OutputSettings().prettyPrint(false)); //makes html() call preserve linebreaks and spacing
    return Jsoup.clean(document.html(),
        "",
        Whitelist.none(),
        new Document.OutputSettings().prettyPrint(false));
  }

  public static void main(String... args)
  {
    File input = new File("/path/to/some/input.html"); //Just replace the input with you own html file source
    Document document;
    try
    {
      document = Jsoup.parse(input, "UTF-8");
      String printOut = new HtmlWithLineBreaks().getCleanHtml(document);
      System.out.println(printOut);
    } catch (IOException e)
    {
      e.printStackTrace();
    } 
  }

}

可选如果您对提供的输出不满意,您可以在 <h1> <div> 包装器之后插入自定义换行符:

public String getCleanHtml(Document document)
{
  document.outputSettings(new Document.OutputSettings().prettyPrint(false));
  document.select("h1").parents().select("div").append("\n"); // Insert a linebreak after the h1 div parent.
  return Jsoup.clean(document.html(),
      "",
      Whitelist.none(),
      new Document.OutputSettings().prettyPrint(false));
}

【讨论】:

  • 它不理解 <DIV><H1> 标签在每个结束后插入 \n。所以输出会像第一个
  • 你试一试了吗?我假设没有,因为代码已经引入了我刚刚纠正的错误。
  • 我还更新了有关如何插入显式换行符的答案,即使Jsoup 了解您的内联块并相应地包装它们。
猜你喜欢
相关资源
最近更新 更多
热门标签