簡體   English   中英

如何保留標簽的含義,如<br> ,<ul> ,<li> ,<p> 等使用 JSOUP 庫在 Java 中讀取它們時?

[英]How to preserve the meaning of tags like <br>, <ul> , <li> , <p> etc when reading them in Java using JSOUP library?

我正在編寫一個從本地 HTML 文件中提取某些特定信息的程序。 然后該信息顯示在 Java JFrame 上並導出到 excel 文件。 (我使用 JSoup 1.9.2 庫進行 HTML 解析)

我遇到了一個問題,每當我從 HTML 文件中提取任何內容時,JSoup 都沒有考慮像斷點標簽、行標簽等 HTML 標簽,因此,所有信息都像一大塊數據一樣被提取,沒有任何適當的換行符或格式。

舉個例子,如果這是我想讀取的數據:

標題

1號線

2號線

    無序列表
  • 元素 1
  • 元素 2

數據返回如下:

標題行 1 行 2 無序列表元素 1 元素 2(即忽略所有 HTML 標簽)

這是我用於閱讀的代碼段:

private String getTitle(Document doc) { // doc is the local HTML file
    Elements title = doc.select(".title");
    for (Element id : title) {
     return id.text();
    }
    return "No Title Available ";
}

任何人都可以向我建議一種可以用來保留 HTML 標簽背后含義的方法,我可以使用它在 JFrame 上顯示數據並將其導出為具有更易讀格式的 excel 嗎?

謝謝。

只是為了給大家一個更新,我能夠找到格式問題的解決方案(更像是一種解決方法)。 我現在正在做的是使用id.html()提取完整的 HTML,我將其存儲在 String 對象中。 然后,我使用帶有正則表達式的字符串函數replaceAll()來刪除所有 HTML 標記,而不會將所有內容都推入一行。 replaceAll()函數類似於replaceAll("\\\\<[^>]*>","") function looks something like :我的整個函數看起來像:

private String processHTML(String initial) { //initial is the String with all the HTML tags
        String modified = initial;
        modified = modified.replaceAll("\\<[^>]*>",""); //regular expression used
        modified = modified.trim(); //To get rid of any unwanted space before and after the needed data
        //All the replaceAll() functions below are to get rid of any HTML entities that might be left in the data extarcted from the HTML
        modified = modified.replaceAll("&nbsp;", " ");
        modified = modified.replaceAll("&lt;", "<");
        modified = modified.replaceAll("&gt;", ">");
        modified = modified.replaceAll("&amp;", "&");
        modified = modified.replaceAll("&quot;", "\"");
        modified = modified.replaceAll("&apos;", "\'");
        modified = modified.replaceAll("&cent;", "¢");
        modified = modified.replaceAll("&copy;", "©");
        modified = modified.replaceAll("&reg;", "®");
        return modified;
    }

再次感謝大家幫助我解決這個問題

干杯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM