在獲取html頁面的全文(使用tika或jsoup)時,是否有可能在每個「li」元素之間有回車符?帶有jsoup或tika的getText():有li元素並帶回車
今天我用緊湊的方式把所有的文字。
感謝
在獲取html頁面的全文(使用tika或jsoup)時,是否有可能在每個「li」元素之間有回車符?帶有jsoup或tika的getText():有li元素並帶回車
今天我用緊湊的方式把所有的文字。
感謝
這是Andrew Phillips的改進版本。
的Java
package com.github.davidepastore.stackoverflow33947074;
import java.io.IOException;
import java.io.InputStream;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
/**
* Stackoverflow 33947074
*
*/
public class App
{
public static void main(String[] args) throws IOException {
ClassLoader classloader = Thread.currentThread()
.getContextClassLoader();
InputStream is = classloader.getResourceAsStream("file.html");
Document document = Jsoup.parse(is, "UTF-8", "");
Element element = document.select("html").first();
String text = getText(element);
System.out.println("Result: " + text);
}
/**
* Get the custom text from the given {@link Element}.
* @param element The {@link Element} from which get the custom text.
* @return Returns the custom text.
*/
private static String getText(Element element) {
String working = "";
for (Node child : element.childNodes()) {
if (child instanceof TextNode) {
working += ((TextNode) child).text();
}
if (child instanceof Element) {
Element childElement = (Element)child;
if (childElement.tag().getName().equalsIgnoreCase("li")) {
working += "\n";
}
working += getText(childElement);
}
}
return working;
}
}
file.html
<html>
<head>
<title>Try jsoup</title>
</head>
<body>
<p>This is <a href="http://jsoup.org/">jsoup</a>.</p>
<ul>
<li>First element</li>
<li><a href="#">Second element</a></li>
<li>Third element <b>Additional for third element</b></li>
</ul>
</body>
</html>
輸出
Result: Try jsoup This is jsoup.
First element
Second element
Third element Additional for third element
謝謝你的回答。我今天下午會嘗試。問候 – user1660655
謝謝。使用Tika時,我會重載endElement事件並在li元素到達時追加\ n。 – user1660655
請註明出處HTML的一個例子,EXPEC特德輸出,所以我可以幫助你:) –
這聽起來像你有一些代碼,幾乎你想要的,但不完全。如果您向我們展示您已完成的工作以及您想要取得的輸出結果,則您更有可能獲得有用的幫助。 –