Backtestsjsouprun-20261006-181938#2532

Issue #2532 Merged fix PR # Run 6 Oct 2026 · run-20261006-181938 jhy/jsoup

Element.html(Appendable) violates the contract of Node.html(Appendable)

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches fix the issue the same way: they make `Node#outerHtml(Appendable)` public so an element's outer HTML can be streamed. Both also document that `Element#html(Appendable)` writes inner HTML, consistent with `html()`. Both handle `Document` so it writes no wrapper tag.

Patch A does this with the smallest possible change. It widens the visibility from protected to public and keeps the `void` signature, which is binary- and source-compatible. It adds a `Document` override that delegates to `html(accum)`. Its tests check the result against `outerHtml()` and `html()`, cover non-element nodes and building a fragment from several elements, and run from outside the `org.jsoup.nodes` package to show the method is now public.

Patch B changes the signature to a generic `<T extends Appendable> T outerHtml(T)`. That breaks binary compatibility, so it has to add a japicmp exclusion in `pom.xml` and argue that no downstream code overrides the method. It also removes `Document#outerHtml()` (String) and instead overrides `outerHtml(QuietAppendable)`. That drops the old `super.html()` path, which trimmed output under pretty-print, so `Document.outerHtml()` may now behave differently. It also refactors `Element#html` into a package-private `QuietAppendable` overload. The return value for chaining is a nicer API, and its tests are also solid, including `assertSame` and prefix checks. But the extra signature changes, the build-config exclusion and the altered `Document.outerHtml()` path add risk without being needed to fix the issue.

On correctness and tests the two are about equal, and A's scope is tighter and lower-risk, so A wins.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

10m 52s

Wall-clock time in the container

Full test suite

No new failures

2,087 passed · 0 skipped · 2,087 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

74vs 119 merged

Changed lines, ours vs merged

The contract of Node.html(Appendable) states: "Write this node and its children to the given Appendable", but if you call Element.html(Appendable) only the children of the Element are appended:

https://github.com/jhy/jsoup/blob/d8c49e5ec72a08ca1ac4e08740e70dc0f47ad911/src/main/java/org/jsoup/nodes/Element.java#L2047

On the other hand, Node.outerHtml(Appendable) is protected, and the class Printer is not visible too.

It would be very useful to have a method to write all the HTML of an element and its content, especially when one have to generate HTML fragments. The String outerHtml() method is public and does the job, but it's obvious that the version that accept an Appendable is more efficient if the caller has an Appendable ready to use.

The two patches

Our patch+73 −1
CHANGES.mdindex fa9037bd..0c0256a3 100644@@ -9,6 +9,7 @@ * Simplified the HTML tree builder's scope, implied-end-tag, and special-element checks by caching parser-only options on Tag. That improves HTML parser throughput by about 10% on small inputs and up to about 30% on larger inputs in the benchmark fixtures. [#2502](https://github.com/jhy/jsoup/issues/2502) * Improved HTML parser throughput stability by making hot tokeniser scan paths compile more predictably. [#2507](https://github.com/jhy/jsoup/pull/2507) * `<noscript>` fallback markup is now parsed into an inspectable DOM subtree in both the document head and body. The fallback acts as a contained parsing island, so malformed markup cannot disrupt the surrounding document structure, while normal HTML tokenization still applies within it. This also improves round-trip serialization. [#2537](https://github.com/jhy/jsoup/pull/2537)+* Made `Node#outerHtml(Appendable)` public, so an element's outer HTML (including its own tag) can be streamed directly to a `Writer` or other `Appendable` without building an intermediate String. Clarified that `Element#html(Appendable)` writes the element's inner HTML, consistent with `Element#html()`. On a `Document`, `outerHtml(Appendable)` writes the document's content (no wrapper tag), like `Document#html(Appendable)`. * Improved redirect credential handling as a defense-in-depth measure: explicit authorization headers and request cookies are no longer forwarded across origins, reducing exposure through open redirects and aligning with HTTP guidance. Cookies managed by a `CookieStore` continue to follow their configured scope. [#2540](https://github.com/jhy/jsoup/pull/2540)  ### Bug Fixessrc/main/java/org/jsoup/nodes/Document.javaindex db25382f..b410a9a0 100644@@ -231,6 +231,11 @@ public class Document extends Element {         return super.html(); // no outer wrapper tag     } +    @Override+    public void outerHtml(Appendable accum) {+        html(accum); // no outer wrapper tag+    }+     /**      Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared.      @param text un-encoded textsrc/main/java/org/jsoup/nodes/Element.javaindex 82e2d0ff..0f1cfe59 100644@@ -2042,6 +2042,16 @@ public class Element extends Node implements Iterable<Element> {         return NodeUtils.outputSettings(this).prettyPrint() ? html.trim() : html;     } +    /**+     Write this element's inner HTML (its children, but not this element's own tag) to the given {@link Appendable}.+     This is the streaming equivalent of {@link #html()}. To write this element's outer HTML, including its own tag,+     use {@link #outerHtml(Appendable)}.++     @param accum the {@link Appendable} to write to.+     @return the supplied {@link Appendable}, for chaining.+     @throws org.jsoup.SerializationException if the appendable throws an IOException.+     @see #outerHtml(Appendable)+     */     @Override     public <T extends Appendable> T html(T accum) {         Node child = firstChild();src/main/java/org/jsoup/nodes/Node.javaindex 497aaa93..415c0d28 100644@@ -846,7 +846,18 @@ public abstract class Node implements Cloneable {         return StringUtil.releaseBuilder(sb);     } -    protected void outerHtml(Appendable accum) {+    /**+     Write this node's outer HTML (this node and its children) to the given {@link Appendable}. For example, on a+     {@code p} element, may write {@code <p>Para</p>}. This is the streaming equivalent of {@link #outerHtml()}, and+     avoids building an intermediate String when the caller already has an Appendable (such as a {@link java.io.Writer})+     ready.++     @param accum the {@link Appendable} to write to.+     @throws org.jsoup.SerializationException if the appendable throws an IOException.+     @see #outerHtml()+     @see Element#html(Appendable)+     */+    public void outerHtml(Appendable accum) {         outerHtml(QuietAppendable.wrap(accum));     } @@ -867,6 +878,9 @@ public abstract class Node implements Cloneable {      /**      Write this node and its children to the given {@link Appendable}.+     <p>Note that {@link Element} overrides this to write only the element's inner HTML (its children), consistent with+     {@link Element#html()}. To write an element's outer HTML (including its own tag) to an Appendable, use+     {@link #outerHtml(Appendable)}.</p>       @param appendable the {@link Appendable} to write to.      @return the supplied {@link Appendable}, for chaining.src/test/java/org/jsoup/nodes/DocumentTest.javaindex 5d3975e8..7ee24599 100644@@ -197,6 +197,19 @@ public class DocumentTest {     	assertEquals(htmlContent, document.html(new StringWriter()).toString());     } +    @Test public void testOuterHtmlAppendable() {+        // a Document has no wrapper tag, so outerHtml(Appendable) matches outerHtml() and html(Appendable)+        String htmlContent = "<html><head><title>Hello</title></head><body><p>One</p><p>Two</p></body></html>";+        Document document = Jsoup.parse(htmlContent);+        document.outputSettings().prettyPrint(false);++        StringWriter writer = new StringWriter();+        document.outerHtml(writer);+        assertEquals(htmlContent, writer.toString());+        assertEquals(document.outerHtml(), writer.toString());+        assertEquals(document.html(new StringWriter()).toString(), writer.toString());+    }+     @Test public void testOverflowClone() {         StringBuilder sb = new StringBuilder();         sb.append("<head><base href='https://jsoup.org/'>");src/test/java/org/jsoup/select/ElementsTest.javaindex b1b9b3dd..0a7259c1 100644@@ -133,6 +133,35 @@ public class ElementsTest {         assertEquals("<p>Hello</p>\n<p>There</p>", divs.html());     } +    @Test public void publicOuterHtmlAppendable() {+        // outerHtml(Appendable) is public API (this test is outside org.jsoup.nodes); writes the element itself+        Document doc = Jsoup.parse("<div id=a><p>One</p><p>Two</p></div>");+        doc.outputSettings().prettyPrint(false);+        Element div = doc.expectFirst("#a");++        java.io.StringWriter writer = new java.io.StringWriter();+        div.outerHtml(writer);+        assertEquals("<div id=\"a\"><p>One</p><p>Two</p></div>", writer.toString());+        assertEquals(div.outerHtml(), writer.toString());++        // html(Appendable) on an Element remains the inner HTML, consistent with html()+        StringBuilder inner = div.html(new StringBuilder());+        assertEquals("<p>One</p><p>Two</p>", inner.toString());+        assertEquals(div.html(), inner.toString());++        // non-element nodes: html(Appendable) and outerHtml(Appendable) both write the node itself+        Node text = div.child(0).childNode(0);+        StringBuilder textOuter = new StringBuilder();+        text.outerHtml(textOuter);+        assertEquals("One", textOuter.toString());+        assertEquals("One", text.html(new StringBuilder()).toString());++        // generating a fragment from several elements into one Appendable+        StringBuilder frag = new StringBuilder();+        for (Element p : doc.select("p")) p.outerHtml(frag);+        assertEquals("<p>One</p><p>Two</p>", frag.toString());+    }+     @Test public void outerHtml() {         Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>");         Elements divs = doc.select("div"); 
Merged fix · PR #+98 −21
CHANGES.mdindex fa9037bd..3ca16dd0 100644@@ -10,6 +10,7 @@ * Improved HTML parser throughput stability by making hot tokeniser scan paths compile more predictably. [#2507](https://github.com/jhy/jsoup/pull/2507) * `<noscript>` fallback markup is now parsed into an inspectable DOM subtree in both the document head and body. The fallback acts as a contained parsing island, so malformed markup cannot disrupt the surrounding document structure, while normal HTML tokenization still applies within it. This also improves round-trip serialization. [#2537](https://github.com/jhy/jsoup/pull/2537) * Improved redirect credential handling as a defense-in-depth measure: explicit authorization headers and request cookies are no longer forwarded across origins, reducing exposure through open redirects and aligning with HTTP guidance. Cookies managed by a `CookieStore` continue to follow their configured scope. [#2540](https://github.com/jhy/jsoup/pull/2540)+* Elements can now append their outer HTML, including their own tags, directly to an `Appendable` with `Node#outerHtml(Appendable)`, without first creating a `String`. This complements `Element#html(Appendable)`, which appends inner HTML only. [#2532](https://github.com/jhy/jsoup/issues/2532)  ### Bug Fixes * Fixed HTML parsing of mixed-case RCDATA end tags after tag-shaped text. For example, `<title><p>Foo</TiTLE>` and `<textarea><img src=x></TeXtArEa>` now keep the tag-shaped content as text instead of promoting it to markup. [#2503](https://github.com/jhy/jsoup/issues/2503)pom.xmlindex 43b1131f..dc6a49fa 100644@@ -326,7 +326,12 @@             <onlyModified>false</onlyModified>             <breakBuildOnBinaryIncompatibleModifications>true</breakBuildOnBinaryIncompatibleModifications>             <breakBuildOnSourceIncompatibleModifications>true</breakBuildOnSourceIncompatibleModifications>-            <excludes />+            <excludes>+              <!-- outerHtml(Appendable) was an undocumented protected helper; making it a public, chaining API changes+                   its return type and generic signature. No downstream overrides were found in a GitHub code search,+                   so we accept this narrow compatibility break. Remove after oldVersion advances to 1.23.1. -->+              <exclude>org.jsoup.nodes.Node#outerHtml(java.lang.Appendable)</exclude>+            </excludes>             <overrideCompatibilityChangeParameters>               <!-- allows new default and move to default methods. compatible as long as existing binaries aren't making calls via reflection. if so, they need to catch errors anyway. -->               <overrideCompatibilityChangeParameter>src/main/java/org/jsoup/nodes/Document.javaindex db25382f..fccb2ed2 100644@@ -4,6 +4,7 @@ import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.helper.DataUtil; import org.jsoup.helper.Validate;+import org.jsoup.internal.QuietAppendable; import org.jsoup.internal.StringUtil; import org.jsoup.parser.ParseSettings; import org.jsoup.parser.Parser;@@ -226,9 +227,10 @@ public class Document extends Element {         );     } +    /** Append the HTML of this Document to the supplied {@link QuietAppendable}. */     @Override-    public String outerHtml() {-        return super.html(); // no outer wrapper tag+    protected void outerHtml(QuietAppendable accum) {+        html(accum);     }      /**src/main/java/org/jsoup/nodes/Element.javaindex 82e2d0ff..efc34a67 100644@@ -2029,11 +2029,12 @@ public class Element extends Node implements Iterable<Element> {     }      /**-     * Retrieves the element's inner HTML. E.g. on a {@code <div>} with one empty {@code <p>}, would return-     * {@code <p></p>}. (Whereas {@link #outerHtml()} would return {@code <div><p></p></div>}.)-     *-     * @return String of HTML.-     * @see #outerHtml()+     Get the inner HTML of this element. For example, on a {@code <div>} with one empty {@code <p>}, this returns+     {@code <p></p>}, whereas {@link #outerHtml()} returns {@code <div><p></p></div>}.++     @return the inner HTML of this element+     @see #html(Appendable)+     @see #outerHtml()      */     public String html() {         StringBuilder sb = StringUtil.borrowBuilder();@@ -2042,17 +2043,32 @@ public class Element extends Node implements Iterable<Element> {         return NodeUtils.outputSettings(this).prettyPrint() ? html.trim() : html;     } +    /**+     Append the inner HTML of this element to the supplied {@link Appendable}.++     @param appendable the {@link Appendable} that will receive the HTML+     @return the supplied {@link Appendable}, for chaining+     @throws org.jsoup.SerializationException if the appendable throws an IOException+     @see #html()+     @see #outerHtml(Appendable)+     @see #outerHtml()+     */     @Override-    public <T extends Appendable> T html(T accum) {+    public <T extends Appendable> T html(T appendable) {+        html(QuietAppendable.wrap(appendable));+        return appendable;+    }++    /** Append the inner HTML of this element to the supplied {@link QuietAppendable}. */+    void html(QuietAppendable accum) {         Node child = firstChild();         if (child != null) {-            Printer printer = Printer.printerFor(child, QuietAppendable.wrap(accum));+            Printer printer = Printer.printerFor(child, accum);             while (child != null) {                 printer.traverse(child);                 child = child.nextSibling();             }         }-        return accum;     }      /**src/main/java/org/jsoup/nodes/Node.javaindex 497aaa93..304a51af 100644@@ -835,9 +835,10 @@ public abstract class Node implements Cloneable {     }      /**-     Get the outer HTML of this node. For example, on a {@code p} element, may return {@code <p>Para</p>}.-     @return outer HTML+     Get the outer HTML of this node. For example, on a {@code p} element, this may return {@code <p>Para</p>}.+     @return the outer HTML of this node      @see Element#html()+     @see #outerHtml(Appendable)      @see Element#text()      */     public String outerHtml() {@@ -846,31 +847,52 @@ public abstract class Node implements Cloneable {         return StringUtil.releaseBuilder(sb);     } -    protected void outerHtml(Appendable accum) {-        outerHtml(QuietAppendable.wrap(accum));+    /**+     Append the outer HTML of this node to the supplied {@link Appendable}. This includes the node itself; for example,+     on a {@code p} element this appends {@code <p>Para</p>}. To append only an Element's contents, use+     {@link Element#html(Appendable)}.++     @param appendable the {@link Appendable} that will receive the HTML.+     @return the supplied {@link Appendable}, for chaining.+     @throws org.jsoup.SerializationException if the appendable throws an IOException.+     @see #outerHtml()+     @see Element#html(Appendable)+     @since 1.23.1+     */+    public <T extends Appendable> T outerHtml(T appendable) {+        outerHtml(QuietAppendable.wrap(appendable));+        return appendable;     } +    /** Append the outer HTML of this node to the internal output. */     protected void outerHtml(QuietAppendable accum) {         Printer printer = Printer.printerFor(this, accum);         printer.traverse(this);     }      /**-     Get the outer HTML of this node.--     @param accum accumulator to place HTML into-     @param out+     Append this node's opening or complete HTML to the internal output.+     @param accum the internal output+     @param out the output settings      */     abstract void outerHtmlHead(final QuietAppendable accum, final Document.OutputSettings out); +    /**+     Append this node's closing HTML, if any, to the internal output.+     @param accum the internal output+     @param out the output settings+     */     abstract void outerHtmlTail(final QuietAppendable accum, final Document.OutputSettings out);      /**-     Write this node and its children to the given {@link Appendable}.+     Append the HTML of this node to the supplied {@link Appendable}. For an {@link Element}, this appends the element's+     inner HTML, consistent with {@link Element#html()}. For other node types, this appends the node's outer HTML. -     @param appendable the {@link Appendable} to write to.+     @param appendable the {@link Appendable} that will receive the HTML.      @return the supplied {@link Appendable}, for chaining.      @throws org.jsoup.SerializationException if the appendable throws an IOException.+     @see Element#html(Appendable)+     @see #outerHtml(Appendable)      */     public <T extends Appendable> T html(T appendable) {         outerHtml(appendable);src/test/java/org/jsoup/nodes/DocumentTest.javaindex 5d3975e8..3b1e5d39 100644@@ -197,6 +197,24 @@ public class DocumentTest {     	assertEquals(htmlContent, document.html(new StringWriter()).toString());     } +    @Test void outerHtmlAppendableMatchesString() {+        Document doc = Jsoup.parse("<title>One</title><p>Two</p>");+        String expected = "<html>\n" ++            " <head>\n" ++            "  <title>One</title>\n" ++            " </head>\n" ++            " <body>\n" ++            "  <p>Two</p>\n" ++            " </body>\n" ++            "</html>";++        assertEquals(expected, doc.outerHtml());++        StringBuilder accum = new StringBuilder("Before ");+        assertSame(accum, doc.outerHtml(accum));+        assertEquals("Before " + expected, accum.toString());+    }+     @Test public void testOverflowClone() {         StringBuilder sb = new StringBuilder();         sb.append("<head><base href='https://jsoup.org/'>");src/test/java/org/jsoup/nodes/ElementTest.javaindex b4eab867..827fbdb0 100644@@ -515,6 +515,19 @@ public class ElementTest {         assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html());     } +    @Test void htmlAppendableWritesInnerAndOuterHtml() {+        Element span = new Element("span");+        span.appendElement("b").text("One");++        StringBuilder inner = new StringBuilder("Before ");+        assertSame(inner, span.html(inner));+        assertEquals("Before <b>One</b>", inner.toString());++        StringBuilder outer = new StringBuilder("Before ");+        assertSame(outer, span.outerHtml(outer));+        assertEquals("Before <span><b>One</b></span>", outer.toString());+    }+     @Test void formatNoTrailingSpace() {         // https://github.com/jhy/jsoup/issues/2215         String html = "<html>\n <head></head>\n <body>\n  a\n  <div>\n  </div>\n </body>\n</html>";