使用Jsoup库删除标记

时间:2014-01-07 16:33:47

标签: java java-ee jsoup

我需要删除不需要的标签..任何人都可以指导我如何处理它......我的代码是

public class Test {

    static String val = "<div class=vcard><div class=label>Category: </div><span class=category><a title=Chemicals Manufacturers href=http://www.gmdu.net/list-5-p1.html>Chemicals</a>- <a title=Textile Chemicals Manufacturers href=http://www.gmdu.net/list-5-273-p1.html>Textile Chemicals</a></span><br/><div class=label>Region: </div><span class=adr country-name><a title=Sri Lanka Manufacturers href=http://www.gmdu.net/loca-35-p1.html>Sri Lanka</a></span><span class=fn org>Haycolour (Pvt) Ltd</span><br/></div>";

    public static void main(String a[]) throws IOException
    {
         Document doc = Jsoup.parse(val);
            Elements labels = doc.select("div.vcard div.label");
            for (Element label : labels) {
                System.out.println(String.format("%s:%s", label.text().trim(),label.nextSibling().outerHtml()));
            }
    }
}

我的输出:

Category::<span class="category"><a title="Chemicals" manufacturers="" href="http://www.gmdu.net/list-5-p1.html">Chemicals</a>- <a title="Textile" chemicals="" manufacturers="" href="http://www.gmdu.net/list-5-273-p1.html">Textile Chemicals</a></span>
Region::<span class="adr" country-name=""><a title="Sri" lanka="" manufacturers="" href="http://www.gmdu.net/loca-35-p1.html">Sri Lanka</a></span>

预期产出:

Category:Chemicals - Textile Chemicals
Region:Sri Lanka Haycolour (Pvt) Ltd

1 个答案:

答案 0 :(得分:0)

我发现这对jSoup的nextElementSibling

最容易

我用这个替换了你的println语句:

System.out.println(String.format("%s:%s %s", label.text().trim(),label.nextElementSibling().text().trim(),
label.nextElementSibling().nextElementSibling().text().trim()));

制作此输出:

Category::Chemicals- Textile Chemicals 
Region::Sri Lanka Haycolour (Pvt) Ltd