<h2>This is a heading</h2>
<p>My mother has
<span style="color:blue;font-weight:bold">blue</span>
eyes and my father has
<span style="color:darkolivegreen;font-weight:bold">
dark green</span>
eyes.</p>
<h3>This is another heading<h3>
<p>This is a paragraph</p>
“我的母亲有蓝色眼睛,我的父亲有深绿色眼睛”。我想用JSOUP解析这个sentance,并在android textview上用粗体和彩色文本打印它。这里“蓝色”是粗体和蓝色。 “深绿色”是大胆的颜色。
我需要解析上面的html代码,需要显示如下:
这是标题
我母亲的眼睛是蓝色,我父亲的眼睛是深绿色
这是另一个标题
这是一个段落
以下是我的计划。考虑文档doc ==得到高于html;
Elements eHeadder = doc.select("*");
for (Element eHead : eHeadder) {
String tag = eHead.tagName();
if (tag.equals("p")) {
String pText = eHead.text();
tv.setText(pText);
}else if(tag.equals("h2")){
String pText = eHead.text();
tv.setText(pText);
}else if(tag.equals("h3")){
String pText = eHead.text();
tv.setText(pText);
}
}
答案 0 :(得分:4)
这是你的意思吗?
public static void main(final String[] args)
{
final String html = "<p>My mother has\n" +
"<span style=\"color:blue;font-weight:bold\">blue</span>\n" +
"eyes and my father has\n" +
"<span style=\"color:darkolivegreen;font-weight:bold\">\n" +
"dark green</span>\n" +
"eyes.</p>\n" +
"<h2>Mr. <span style=\"color:green\">Foobar</span></h2>";
final Document document = Jsoup.parse(html);
final Elements textNodes = document.select("p,h2");
for (final Element element : textNodes)
{
System.out.println("Found: " + element.text());
System.out.println("\t Neasted Spawns:");
for (final Element span : element.select("span"))
{
System.out.println("\t\t css: " + span.attr("style"));
}
}
}
它将打印:
Found: My mother has blue eyes and my father has dark green eyes.
Neasted Spawns:
css: color:blue;font-weight:bold
css: color:darkolivegreen;font-weight:bold
Found: Mr. Foobar
Neasted Spawns:
css: color:green