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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With