Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update html file using Jsoup

Tags:

java

html

jsoup

I want to update HTML file using java code, I am able to read attribute using Jsoup but I want to update attribute value and save the same to HTML file

I have tried Jsoup element tag.attr(attrname, value)

Same is not doing anything with my HTML file

like image 879
Hardik Shah Avatar asked May 09 '26 10:05

Hardik Shah


1 Answers

You can just read the html file using java.nio, parse and modify it with Jsoup and save it to a file again using java.nio:

Path input = Path.of("input.html");
Document document = Jsoup.parse(Files.readString(input), "UTF-8");
document.select("#my-id").attr("class", "test");
Path output = Path.of("output.html");
Files.writeString(output, document.outerHtml());

For example if the input file looks like this:

<html>
 <head>
  <title>Foo</title>
 </head>
 <body>
  <div id="my-id">Bar</div>
 </body>
</html>

The output file will be modified like this:

<html>
 <head> 
  <title>Foo</title> 
 </head> 
 <body> 
  <div id="my-id" class="test">Bar</div>  
 </body>
</html>

But remember that the whitespaces of the output file could be different from the input file.

like image 173
Samuel Philipp Avatar answered May 10 '26 23:05

Samuel Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!