kevin sufferdini
kevin sufferdini

Reputation: 121

Jsoup selecting and replacing multiple <a> elements

So I am just trying out the Jsoup API and have a simple question. I have a string and would like to keep the string in tact except when passed through my method. I want the string to pass through this method and take out the elements that wrap the links. Right now I have:

public class jsTesting {
public static void main(String[] args) {
    String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
    Elements select = Jsoup.parse(html).select("a");
    String linkHref = select.attr("href");
    System.out.println(linkHref);       
}}

This returns the first URL unwrapped only. I would like all URLs unwrapped as well as the original string. Thanks in advance

EDIT: SOLUTION:

Thanks alot for the answer and I edited it only slightly to get the results I wanted. Here is the solution in full that I am using:

public class jsTesting {
public static void main(String[] args) {
    String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
    Document doc = Jsoup.parse(html);
    Elements links = doc.select("a[href]");
    for (Element link : links) {
        doc.select("a").unwrap();
    }
    System.out.println(doc.text());
}

}

Thanks again

Upvotes: 0

Views: 3523

Answers (1)

bchetty
bchetty

Reputation: 2241

Here's the corrected code:

public class jsTesting {
    public static void main(String[] args) {
        String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
        Elements links = Jsoup.parse(html).select("a[href]"); // a with href;
        for (Element link : links) {
            //Do whatever you want here
            System.out.println("Link Attr : " + link.attr("abs:href"));
            System.out.println("Link Text : " + link.text());    
        }       
    }
}

Upvotes: 3

Related Questions