Search code examples
javahtmljsoup

Jsoup will not save changes made to HTML


I am trying to alter an HTML file called results.html and changing the ID tag result from a "come back later" text to an output from my program. I can tell I'm opening the file because it is reading the current HTML "come back later" from system.out.print. But nothing is saved in the end

Any tips?

Document document = Jsoup.parse( new File( "C:\\Users\\ctisi\\Documents\\results.html" ) , "utf-8" );
Element resultID = document.getElementById("result");
System.out.println("Outer HTML Before Modification :\n"  + resultID.outerHtml());
resultID.text("This is a sample content.");

Solution

  • You are modifying the in memory representation of the DOM structure as represented by the document object. This will not alter the output file.

    You will need to actually add code to write the modified document back to the file.

    File file=new File("C:\\Users\\ctisi\\Documents\\results.html");
    Document document=Jsoup.parse(file , "utf-8" );
    Element resultID=document.getElementById("result");
    resultID.text("This is a sample content.");
    FileWriter writer=new FileWriter(file);
    writer.write(document.toString());
    writer.flush();
    writer.close();