Parse HTML with jsoup and save the original content.

I want to replace some elements in HTML files, leaving everything else unchanged.

Document doc = Jsoup.parse("<div id=title>Old</div >\n" +
        "<p>1<p>2\n" +
        "<table><tr><td>1</td></tr></table>");
doc.getElementById("title").text("New");
System.out.println(doc.toString());

I expect to get the following result:

<div id=title>New</span></div >
<p>1<p>2
<table><tr><td>1</td></tr></table>

Instead, I have:

<html>
 <head></head>
 <body>
  <div id="title">New</div>
  <p>1</p>
  <p>2 </p>
  <table>
   <tbody>
    <tr>
     <td>1</td>
    </tr>
   </tbody>
  </table>
 </body>
</html>

Added by Jsoup:

  • closing p tags
  • double quotes for attribute values
  • TBODY
  • html, elements of the head and body

Can I convert modified HTML to original? Jericho does this, but he does not provide slick DOM manipulation methods, as Jsoup does.

+5
source share
1 answer

Is there a reason why attribute values ​​should not be specified? See here and here .

For other items, try the following:

final String html = "<div id=title>Old</div >\n"
            + "<p>1<p>2\n"
            + "<table><tr><td>1</td></tr></table>";

Document doc = Jsoup.parse(html);
doc.select("[id=title]").first().text("New");
doc.select("body, head, html, tbody").unwrap();
doc.outputSettings().prettyPrint(false);

System.out.println(doc);
0
source

All Articles