Backtestsjsouprun-20261006-181938#2619
Should not print a void element's children
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches fix the root cause in the same three places: html(), outerHtmlHead, and the Printer traversal. Each suppresses a void element's children only for HTML syntax and the HTML namespace. Patch A changes how Printer traverses. It switches Printer from NodeVisitor to NodeFilter and returns SKIP_ENTIRELY for every HTML void element, including the ordinary childless ones. This has two costs: - SKIP_ENTIRELY suppresses tail() for all void elements, so the pretty and outline printers' addTail logic no longer runs for normal <br>, <img> or <hr>. That is a behavioural change to the common case and risks whitespace regressions. - Changing the interface type is a broad change. Any traverse helper or subclass that relies on NodeVisitor semantics must also adapt, and the diff does not show this. Patch A also leaves outerHtmlTail unguarded, so it relies entirely on the traversal never reaching the tail. Patch B is narrower: - It enters skip mode only when a void element actually has children, so existing output for normal void elements is untouched. - It also guards outerHtmlTail, so no </br> can leak out. - It uses one well-named predicate, serializesAsVoid(out), in all four places. Patch B's tests are stronger. They check that pretty, compact and outline output with injected children is identical to an unmodified document, cover html() and outerHtml(), and confirm the children stay in the DOM and still print in XML syntax. Patch A tests only compact mode, plus XML and a foreign-namespace case; it never exercises the pretty printer, which is where its riskier change matters. B adds no CHANGES entry, which is minor. Overall, B is the safer and better-verified fix.
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
8m 25s
Wall-clock time in the container
Full test suite
No new failures
2,385 passed · 0 skipped · 2,385 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
87vs 66 merged
Changed lines, ours vs merged
The issue
View on GitHubhttps://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments
If current node serializes as void, then continue on to the next child node at this point.
It's possible that via DOM manipulation, a void element gets children. In that case, we should not be printing their content, as it makes for inconsistent output.
The two patches
src/main/java/org/jsoup/nodes/Element.javaindex 8ed39762..e4da659a 100644@@ -2001,12 +2001,12 @@ public class Element extends Node implements Iterable<Element> { accum.append('<').append(tagName); if (attributes != null) attributes.html(accum, out); - if (childNodes.isEmpty()) {+ if (serializesAsVoid(out)) { // html void element; any children are not serialized+ accum.append('>');+ } else if (childNodes.isEmpty()) { boolean xmlMode = out.syntax() == xml || !tag.namespace().equals(NamespaceHtml); if (xmlMode && (tag.is(Tag.SeenSelfClose) || (tag.isKnownTag() && (tag.isEmpty() || tag.isSelfClosing())))) { accum.append(" />");- } else if (!xmlMode && tag.isEmpty()) { // html void element- accum.append('>'); } else { accum.append("></").append(tagName).append('>'); }@@ -2017,9 +2017,18 @@ public class Element extends Node implements Iterable<Element> { @Override void outerHtmlTail(QuietAppendable accum, Document.OutputSettings out) {- if (!childNodes.isEmpty())+ if (!childNodes.isEmpty() && !serializesAsVoid(out)) accum.append("</").append(safeTagName(out.syntax())).append('>');- // if empty, we have already closed in htmlHead+ // if empty, we have already closed in htmlHead; void elements have no end tag+ }++ /**+ Checks if this element serializes as an HTML void element in the given output settings: an HTML syntax output, an+ element in the HTML namespace, and a void (empty) tag. Per the HTML serialization algorithm, such an element has no+ end tag, and its children (which can only be added via DOM manipulation) are not serialized.+ */+ boolean serializesAsVoid(Document.OutputSettings out) {+ return out.syntax() == Document.OutputSettings.Syntax.html && tag.isEmpty() && tag.namespace().equals(NamespaceHtml); } /** Gets the tag name normalized for the output syntax. */@@ -2061,7 +2070,7 @@ public class Element extends Node implements Iterable<Element> { /** Append the inner HTML of this element to the supplied {@link QuietAppendable}. */ void html(QuietAppendable accum) { Node child = firstChild();- if (child != null) {+ if (child != null && !serializesAsVoid(NodeUtils.outputSettings(this))) { Printer printer = Printer.printerFor(child, accum); while (child != null) { printer.traverse(child);src/main/java/org/jsoup/nodes/Printer.javaindex f41f1cc3..16c47611 100644@@ -14,6 +14,8 @@ class Printer implements NodeVisitor { final Node root; final QuietAppendable accum; final OutputSettings settings;+ /** If set, the void element whose (unserialized) children are currently being traversed. */+ @Nullable Element voidEl; Printer(Node root, QuietAppendable accum, OutputSettings settings) { this.root = root;@@ -54,13 +56,23 @@ class Printer implements NodeVisitor { @Override public void head(Node node, int depth) {+ if (voidEl != null) return; // within a void element's children, which are not serialized if (node.getClass() == TextNode.class) addText((TextNode) node, 0, depth); // Excludes CData; falls to addNode- else if (node instanceof Element) addHead((Element) node, depth);+ else if (node instanceof Element) {+ Element el = (Element) node;+ addHead(el, depth);+ if (el.childNodeSize() > 0 && el.serializesAsVoid(settings))+ voidEl = el; // skip its children (and its tail), until we leave it+ } else addNode((LeafNode) node, depth); } @Override public void tail(Node node, int depth) {+ if (voidEl != null) {+ if (node == voidEl) voidEl = null; // a void element has no end tag+ return;+ } if (node instanceof Element) { // otherwise a LeafNode addTail((Element) node, depth); }src/test/java/org/jsoup/nodes/PrinterTest.javaindex 34b5a696..9961d761 100644@@ -90,4 +90,56 @@ public class PrinterTest { assertEquals("<div>\n <span>Span</span> Text <span>Follow</span>\n</div>\n<p><span>Span</span> Text <span>Follow</span></p>", body.html()); } ++ @Test void voidElementChildrenNotPrinted() {+ // https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments : void elements' children are skipped+ Document doc = Jsoup.parse("<p>One <img src=foo> Two <br> Three</p>");+ Element img = doc.expectFirst("img");+ img.appendText("Hidden").appendElement("span").text("Nested");+ doc.expectFirst("br").appendElement("b").text("Also");++ Element p = doc.expectFirst("p");+ String expected = "<p>One <img src=\"foo\"> Two <br> Three</p>";++ // pretty: same as the unmodified document+ Document clean = Jsoup.parse("<p>One <img src=foo> Two <br> Three</p>");+ assertEquals(clean.expectFirst("p").outerHtml(), p.outerHtml());+ assertEquals("<p>One <img src=\"foo\"> Two\n <br>\n Three</p>", p.outerHtml());+ assertEquals("<img src=\"foo\">", img.outerHtml());+ assertEquals("", img.html());++ // compact+ doc.outputSettings().prettyPrint(false);+ assertEquals(expected, p.outerHtml());+ assertEquals("One <img src=\"foo\"> Two <br> Three", p.html());+ assertEquals("<img src=\"foo\">", img.outerHtml());+ assertEquals("", img.html());++ // outline+ doc.outputSettings().prettyPrint(true).outline(true);+ clean.outputSettings().outline(true);+ assertEquals(clean.expectFirst("p").outerHtml(), p.outerHtml());+ assertEquals("<img src=\"foo\">", img.outerHtml());+ assertEquals("", img.html());++ // children are still in the DOM+ assertEquals("HiddenNested", img.text());+ }++ @Test void voidElementWithChildrenPrettyMatchesEmpty() {+ String html = "<div><p>Hello</p><hr><p>There</p></div>";+ Document doc = Jsoup.parse(html);+ Document modified = Jsoup.parse(html);+ modified.expectFirst("hr").appendElement("p").text("Hidden");+ assertEquals(doc.body().html(), modified.body().html());+ assertEquals(doc.html(), modified.html());+ }++ @Test void voidElementChildrenPrintedInXmlSyntax() {+ Document doc = Jsoup.parse("<p><img src=foo></p>");+ doc.expectFirst("img").appendText("Shown");+ doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).prettyPrint(false);+ assertEquals("<p><img src=\"foo\">Shown</img></p>", doc.expectFirst("p").outerHtml());+ assertEquals("Shown", doc.expectFirst("img").html());+ } }
CHANGES.mdindex d8e958ac..5525e0eb 100644@@ -24,6 +24,7 @@ * Template parsing now closes unclosed templates at EOF and handles forms correctly in template documents and fragments. [#2614](https://github.com/jhy/jsoup/issues/2614) * Fixed handling of null characters and initial newlines in HTML to better match the HTML spec, including `pre`, `listing`, and `textarea` elements. Leading newlines in these elements' text are preserved when saving and reparsing HTML. [#2616](https://github.com/jhy/jsoup/pull/2616) * Fixed several HTML parsing edge cases across malformed doctypes, misplaced text in tables, and whitespace in framesets to match the HTML spec. [#2618](https://github.com/jhy/jsoup/pull/2618)+* If a HTML void element ends up with children (via DOM manipulation), those are no longer serialized in `html()`. [#2619](https://github.com/jhy/jsoup/issues/2619) ## 1.23.2 (2026-Aug-26) src/main/java/org/jsoup/nodes/Element.javaindex 8ed39762..b7d9797d 100644@@ -34,6 +34,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import static org.jsoup.internal.Normalizer.asciiLowerCase;+import static org.jsoup.nodes.Document.OutputSettings.Syntax.html; import static org.jsoup.nodes.Document.OutputSettings.Syntax.xml; import static org.jsoup.nodes.TextNode.lastCharIsWhitespace; import static org.jsoup.parser.Parser.NamespaceHtml;@@ -2001,11 +2002,12 @@ public class Element extends Node implements Iterable<Element> { accum.append('<').append(tagName); if (attributes != null) attributes.html(accum, out); - if (childNodes.isEmpty()) {+ boolean htmlVoid = out.syntax() == html && isHtmlVoid();+ if (childNodes.isEmpty() || htmlVoid) { boolean xmlMode = out.syntax() == xml || !tag.namespace().equals(NamespaceHtml); if (xmlMode && (tag.is(Tag.SeenSelfClose) || (tag.isKnownTag() && (tag.isEmpty() || tag.isSelfClosing())))) { accum.append(" />");- } else if (!xmlMode && tag.isEmpty()) { // html void element+ } else if (htmlVoid) { accum.append('>'); } else { accum.append("></").append(tagName).append('>');@@ -2022,6 +2024,11 @@ public class Element extends Node implements Iterable<Element> { // if empty, we have already closed in htmlHead } + /** Tests if this element is an HTML-namespace void tag. */+ boolean isHtmlVoid() {+ return tag.namespace().equals(NamespaceHtml) && tag.isEmpty();+ }+ /** Gets the tag name normalized for the output syntax. */ private String safeTagName(Document.OutputSettings.Syntax syntax) { return syntax == xml ? Attribute.getValidKey(tagName(), xml) : tagName();@@ -2060,6 +2067,7 @@ public class Element extends Node implements Iterable<Element> { /** Append the inner HTML of this element to the supplied {@link QuietAppendable}. */ void html(QuietAppendable accum) {+ if (NodeUtils.outputSettings(this).syntax() == html && isHtmlVoid()) return; Node child = firstChild(); if (child != null) { Printer printer = Printer.printerFor(child, accum);src/main/java/org/jsoup/nodes/Printer.javaindex f41f1cc3..29025a93 100644@@ -4,13 +4,14 @@ import org.jsoup.internal.QuietAppendable; import org.jsoup.internal.StringUtil; import org.jsoup.nodes.Document.OutputSettings; import org.jsoup.parser.Tag;-import org.jsoup.select.NodeVisitor;+import org.jsoup.select.NodeFilter; import org.jspecify.annotations.Nullable; +import static org.jsoup.nodes.Document.OutputSettings.Syntax.html; import static org.jsoup.parser.Parser.NamespaceHtml; /** Base Printer */-class Printer implements NodeVisitor {+class Printer implements NodeFilter { final Node root; final QuietAppendable accum; final OutputSettings settings;@@ -24,7 +25,7 @@ class Printer implements NodeVisitor { void addHead(Element el, int depth) { el.outerHtmlHead(accum, settings); // HTML consumes one initial newline; supply LF so preserved LF or CR text survives a reparse- if (settings.syntax() == OutputSettings.Syntax.html && el.tag().namespace().equals(NamespaceHtml)+ if (settings.syntax() == html && el.tag().namespace().equals(NamespaceHtml) && StringUtil.in(el.normalName(), InitialNewlineTags) && el.firstChild() instanceof TextNode) { String text = ((TextNode) el.firstChild()).getWholeText();@@ -53,17 +54,19 @@ class Printer implements NodeVisitor { } @Override- public void head(Node node, int depth) {+ public FilterResult head(Node node, int depth) { if (node.getClass() == TextNode.class) addText((TextNode) node, 0, depth); // Excludes CData; falls to addNode else if (node instanceof Element) addHead((Element) node, depth); else addNode((LeafNode) node, depth);++ return node instanceof Element && settings.syntax() == html && ((Element) node).isHtmlVoid()+ ? FilterResult.SKIP_ENTIRELY : FilterResult.CONTINUE; // skip any children in void tags } @Override- public void tail(Node node, int depth) {- if (node instanceof Element) { // otherwise a LeafNode- addTail((Element) node, depth);- }+ public FilterResult tail(Node node, int depth) {+ if (node instanceof Element) addTail((Element) node, depth); // otherwise a LeafNode+ return FilterResult.CONTINUE; } /** Pretty Printer */src/test/java/org/jsoup/nodes/ElementTest.javaindex 3f07a097..ce44cefa 100644@@ -3570,4 +3570,38 @@ public class ElementTest { assertEquals(1, actualSize); assertEquals(1, reported); // was 0 via cache }++ @Test void htmlVoidPrintOmitsDomChildren() {+ Document doc = new Document("");+ doc.outputSettings().prettyPrint(false);+ Element span = new Element("span");+ Element br = new Element("br");+ br.appendElement("a").text("hidden");+ span.appendChild(br);+ span.appendElement("b").text("shown");+ doc.appendChild(span);++ assertEquals(1, br.childNodeSize());+ assertEquals("", br.html());+ assertEquals("<br>", br.outerHtml());+ assertEquals("<br><b>shown</b>", span.html());+ assertEquals("<span><br><b>shown</b></span>", span.outerHtml());++ doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);+ assertEquals("<a>hidden</a>", br.html());+ assertEquals("<br><a>hidden</a></br>", br.outerHtml());+ assertEquals("<span><br><a>hidden</a></br><b>shown</b></span>", span.outerHtml());+ }++ @Test void foreignElementWithVoidNameRetainsChildren() {+ Document doc = new Document("");+ doc.outputSettings().prettyPrint(false);+ Element foreignBr = new Element("br", Parser.NamespaceSvg);+ foreignBr.appendElement("a").text("kept");+ doc.appendChild(foreignBr);++ assertEquals("<a>kept</a>", foreignBr.html());+ assertEquals("<br><a>kept</a></br>", foreignBr.outerHtml());+ }+ }