Replace text in HTML element and update the same file with Jsoup

69 views Asked by At

I have been trying for a while to edit the text within an element, but I've not had much luck finding similar examples. Those that I have found haven't worked.

The code I have at the moment is pretty much the same as shown in the Jsoup docs

Java

public void updateTitle() {
        Element content = doc.body().getElementById("titleCER");
        System.out.println(content); // Prints '<p class="certificate-CcM" id="titleCER">CERTIFICATE</p>'
        content.text().replaceAll("text", "Change to this"); // does nothing
        content.text("change to this!"); // does nothing
    }

HTML

<p class="certificate-CcM" id="titleCER">CERTIFICATE</p>

Right now when the code runs, it finds the element by ID fine, but then doesn't update anything in the HTML file

Thank you for any help

2

There are 2 answers

0
Will Jordan On

I was never writing the edited Document back to the HTML file

The solution is:

public void updateTitle() throws IOException {
        Element content = doc.body().getElementById("titleCER");
        System.out.println(content);
        content.text("change to this!");
        PrintWriter writer = new PrintWriter(input,"UTF-8");
        writer.write(doc.html() ) ;
        writer.flush();
        writer.close();
    }

where 'input' is:

File input = new File("/origionalFile.html");
1
Ritesh Singh On

Jsoup's text() method is used for retrieving the text content of an element, but to modify the text, you should use the text(String text) method.

public void updateTitle() {
        Element content = doc.body().getElementById("titleCER");
        if (content != null) {
            // Update text content using the text(String text) method
            content.text("Change to this!");
            System.out.println(content); // Prints the updated element
        } else {
            System.out.println("Element not found");
        }
    }