问题描述
我正在尝试使用Jsoup解析HTML文件并删除html标签.每当我删除HTML标记时,我都希望使用定界符(句号)代替该标记.
I am trying to parse an HTML file using Jsoup and removing the html tags. Whenever I remove an HTML tag I want a delimiter(fullstop) instead of the tag.
例如,如果html是:
for example if the html is:
<head> <title>N-gram and Fast Pattern Extraction Algorithm - CodeProject</title>
<head> <title>N-gram and Fast Pattern Extraction Algorithm - CodeProject</title>
我希望输出为
..N-gram and Fast Pattern Extraction Algorithm - CodeProject.
我是Jsoup的新手.可以使用Jsoup吗?
I am a newcomer to Jsoup. Is it possible using Jsoup?
推荐答案
小心递归.对于较大的DOM,可能会在内存方面或性能方面引起问题.
Be careful with the recursion. For a big DOM it might cause you problems, memory-wise or performance-wise.
import java.util.ListIterator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
public class Main {
public static void main(String[] args) {
try {
String html = "<html><head>" +
"<title>Introduction</title>" +
"</head>" +
"<body>" +
"<a target=\"_top\" href=\"/tags/ref_eventattributes.asp\">HTML Events</a>"+
"<a target=\"_top\" href=\"/tags/ref_canvas.asp\">HTML Canvas</a>"+
"<a target=\"_top\" href=\"/tags/ref_av_dom.asp\">HTML Audio/Video</a>"+
"<a target=\"_top\" href=\"/tags/ref_html_dtd.asp\">HTML Doctypes</a></body></html>";
Document doc = Jsoup.parse(html);
System.out.println(doc);
System.out.println("\n------------------------------------------------------\n");
replaceTag(doc.children());
System.out.println(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void replaceTag(Elements els) {
ListIterator<Element> iter = els.listIterator();
while(iter.hasNext()) {
Element el = iter.next();
replaceTag(el.children());
if(el.parentNode() != null)
el.replaceWith(new TextNode("." + el.text().trim() + ".", ""));
}
}
}
这篇关于Jsoup解析添加定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!