Reputation: 31
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
Upvotes: 3
Views: 2358
Reputation: 11042
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.
Upvotes: 2