【问题标题】:Formatting text output of html with jSoup使用 jSoup 格式化 html 的文本输出
【发布时间】:2013-10-28 20:36:17
【问题描述】:

我有一个要解析的文档,它包含 html,我想将其从 html 转换为 plaintext 但带有格式。

示例摘录

<p>My simple paragragh</p>
<p>My paragragh with <a>Link</a></p>
<p>My paragragh with an <img/></p>

我可以很容易地做这个简单的例子(可能效率不高)

StringBuilder sb = new StringBuilder();

for(Element element : doc.getAllElements()){
    if(element.tag().getName().equals("p")){
        sb.append(element.text());
        sb.append("\n\n");
    }
}

是否可以(以及我将如何做)在正确的位置插入内联元素的输出。一个例子:

<p>My paragragh with <a>Link</a> in the middle</p> 

会变成:

My paragragh with (Location: http://mylink.com) in the middle

【问题讨论】:

    标签: java html-parsing jsoup text-parsing


    【解决方案1】:

    您可以用TextNode 替换每个链接标签:

    final String html = "<p>My simple paragragh</p>\n"
            + "<p>My paragragh with <a>Link</a></p>\n"
            + "<p>My paragragh with an <img/></p>";
    
    Document doc = Jsoup.parse(html, "");
    
    // Select all link-tags and replace them with TextNodes
    for( Element element : doc.select("a") )
    {
        element.replaceWith(new TextNode("(Location: http://mylink.com)", ""));
    }
    
    
    StringBuilder sb = new StringBuilder();
    
    // Format as needed
    for( Element element : doc.select("*") )
    {
        // An alternative to the 'if'-statement
        switch(element.tagName())
        {
            case "p":
                sb.append(element.text()).append("\n\n");
                break;
            // Maybe you have to format some other tags here too ...
        }
    }
    
    System.out.println(sb);
    

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多