Backtestsjsouprun-20261006-181938#2571

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

XML doctype system IDs can serialize as invalid XML

Better

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 the same way: when the system identifier contains a double quote, they delimit it with single quotes and leave the value unchanged. This matches the fix the issue asks for, and neither patch alters the stored identifier. Patch A applies the change only to the system ID, which is exactly the scope of the issue, and adds a CHANGES.md entry. Patch B moves the logic into a small `appendQuoted` helper and also applies it to the public ID. That goes beyond the ask, but it is low-risk and consistent: XML public IDs cannot legally contain `"`, so it only affects input from the HTML parser or programmatic construction, where it prevents the same malformed output. It is neutral rather than harmful. The deciding difference is the tests. Patch A has one test with two round-trip assertions, which is enough to fail before the fix and pass after it. Patch B's tests are more substantive. They reproduce the exact scenario from the issue, check that `systemId()` holds the unescaped value, and verify that reparsing the serialized output preserves the identifier. They also cover the HTML parser path, confirm that a single quote inside the ID still gets double quotes, and test mixed public and system IDs. Patch A's inline comment and changelog entry are good touches, but Patch B's helper is clearly documented and its broader, meaningful tests give more confidence the fix holds.

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

6m 57s

Wall-clock time in the container

Full test suite

No new failures

2,161 passed · 0 skipped · 2,161 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

52vs 19 merged

Changed lines, ours vs merged

I bumped into this odd edge case while importing some old technical documentation.

XML system literals in a doctype can use either single or double quotes as their delimiter.

jsoup accepts the valid XML below, but DocumentType currently always serializes the system identifier using double quotes:

String xml = "<!DOCTYPE root SYSTEM 'a\"b.dtd'><root />";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());

System.out.println(doc.outerHtml());
// <!DOCTYPE root SYSTEM "a"b.dtd"><root />

Escaping the quote as &quot; doesn't work because entity references are not interpreted inside a system literal; it would change the identifier’s value. Converting it to %22 would also change the stored identifier, and the XML external-identifier specification says URI escaping should happen only when necessary and as late as possible during dereferencing.

The fix will be to continue using double quotes normally, but use single quotes when the system identifier contains a double quote.

The two patches

Our patch+50 −2
src/main/java/org/jsoup/nodes/DocumentType.javaindex 19148049..0170df4e 100644@@ -99,15 +99,25 @@ public class DocumentType extends LeafNode {         if (has(PubSysKey))             accum.append(" ").append(attr(PubSysKey));         if (has(PublicId))-            accum.append(" \"").append(attr(PublicId)).append('"');+            appendQuoted(accum, attr(PublicId));         if (has(SystemId))-            accum.append(" \"").append(attr(SystemId)).append('"');+            appendQuoted(accum, attr(SystemId));         if (attributes().hasKey(InternalSubsetKey)) // only if via the xml parser; html parser will drop             accum.append(" [").append(attr(InternalSubsetKey)).append(']');         accum.append('>');     }  +    /**+     Appends the identifier as a quoted literal. Entity references and escapes are not interpreted within doctype+     literals, so the value is emitted as-is; double quotes are used unless the value contains one, in which case single+     quotes are used.+     */+    private static void appendQuoted(QuietAppendable accum, String value) {+        char quote = value.indexOf('"') >= 0 ? '\'' : '"';+        accum.append(" ").append(quote).append(value).append(quote);+    }+     private boolean has(final String attribute) {         return !StringUtil.isBlank(attr(attribute));     }src/test/java/org/jsoup/nodes/DocumentTypeTest.javaindex b4a5b8d4..e12953f1 100644@@ -5,6 +5,7 @@ import org.jsoup.parser.Parser; import org.junit.jupiter.api.Test;  import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows;  /**@@ -72,6 +73,43 @@ public class DocumentTypeTest {         assertEquals(emptySubset, xmlOutput(emptySubset));     } +    @Test void systemIdWithDoubleQuoteUsesSingleQuotes() {+        String xml = "<!DOCTYPE root SYSTEM 'a\"b.dtd'><root />";+        Document doc = Jsoup.parse(xml, "", Parser.xmlParser());+        DocumentType doctype = doc.documentType();+        assertNotNull(doctype);+        assertEquals("a\"b.dtd", doctype.systemId());+        assertEquals("<!DOCTYPE root SYSTEM 'a\"b.dtd'>", doctype.outerHtml());+        assertEquals("<!DOCTYPE root SYSTEM 'a\"b.dtd'><root />", doc.outerHtml());++        // reparsing the output keeps the same identifier+        Document reparsed = Jsoup.parse(doc.outerHtml(), "", Parser.xmlParser());+        assertEquals("a\"b.dtd", reparsed.documentType().systemId());++        // without a double quote, keeps using double quotes (including when it contains a single quote)+        assertEquals("<!DOCTYPE root SYSTEM \"a'b.dtd\">", xmlOutput("<!DOCTYPE root SYSTEM \"a'b.dtd\">"));+        assertEquals("<!DOCTYPE root SYSTEM \"ab.dtd\">", xmlOutput("<!DOCTYPE root SYSTEM 'ab.dtd'>"));+    }++    @Test void systemIdWithDoubleQuoteInHtml() {+        String html = "<!DOCTYPE html SYSTEM 'a\"b.dtd'>";+        assertEquals("<!DOCTYPE html SYSTEM 'a\"b.dtd'>", htmlOutput(html));+        DocumentType reparsed = (DocumentType) Jsoup.parse(htmlOutput(html)).childNode(0);+        assertEquals("a\"b.dtd", reparsed.systemId());+    }++    @Test void publicAndSystemIdsQuotedIndependently() {+        DocumentType constructed = new DocumentType("root", "-//pub\"id//", "sys\"id.dtd");+        assertEquals("<!DOCTYPE root PUBLIC '-//pub\"id//' 'sys\"id.dtd'>", constructed.outerHtml());++        String mixed = "<!DOCTYPE root PUBLIC \"-//W3C//DTD//EN\" 'a\"b.dtd'>";+        assertEquals("<!DOCTYPE root PUBLIC \"-//W3C//DTD//EN\" 'a\"b.dtd'>", xmlOutput(mixed));+        assertEquals("<!DOCTYPE root PUBLIC \"-//W3C//DTD//EN\" 'a\"b.dtd'>", htmlOutput(mixed));++        String publicQuote = "<!DOCTYPE html PUBLIC 'a\"b' \"c.dtd\">";+        assertEquals("<!DOCTYPE html PUBLIC 'a\"b' \"c.dtd\">", htmlOutput(publicQuote));+    }+     private String htmlOutput(String in) {         DocumentType type = (DocumentType) Jsoup.parse(in).childNode(0);         return type.outerHtml(); 
Merged fix · PR #+17 −2
CHANGES.mdindex f5873d51..f697d8da 100644@@ -19,6 +19,7 @@   * With namespace awareness disabled, inherited and undeclared prefixes now receive the declarations needed for XML serialization.   * Valid HTML names that are not XML QNames, such as `a:b:c`, are normalized. Attributes that still cannot be represented are skipped, and unrepresentable elements no longer change the surrounding tree. * Fixed `W3CDom` conversion of programmatically created or renamed elements whose names can be represented in a jsoup HTML DOM but are not valid XML names, such as `1abc`. These names are now normalized (e.g. `_1abc`) instead of causing a `NullPointerException`. [#2560](https://github.com/jhy/jsoup/issues/2560)+* Fixed XML doctype serialization when a system identifier contains a double quote, which could otherwise produce invalid XML. [#2571](https://github.com/jhy/jsoup/issues/2571) * Fixed the JDK `HttpClient` implementation to accept responses without a `Content-Type` header, matching the `HttpURLConnection` implementation. [#2549](https://github.com/jhy/jsoup/pull/2549) * Fixed HTTP response content-type matching to handle media types case-insensitively and recognize structured `+xml` suffixes, including vendor-specific media types. [#2550](https://github.com/jhy/jsoup/pull/2550) * Corrected multipart form encoding to percent-escape CR and LF in field names and filenames, matching the HTML form submission specification. Multipart file content-types containing CR or LF are now rejected with a `ValidationException`. [#2555](https://github.com/jhy/jsoup/pull/2555)src/main/java/org/jsoup/nodes/DocumentType.javaindex 19148049..4632b6b7 100644@@ -100,8 +100,13 @@ public class DocumentType extends LeafNode {             accum.append(" ").append(attr(PubSysKey));         if (has(PublicId))             accum.append(" \"").append(attr(PublicId)).append('"');-        if (has(SystemId))-            accum.append(" \"").append(attr(SystemId)).append('"');+        if (has(SystemId)) {+            String systemId = attr(SystemId);+            // system IDs can contain quotes; keep the value unchanged and use the other delimiter+            // https://www.w3.org/TR/xml/#sec-external-ent+            char quote = systemId.indexOf('"') >= 0 ? '\'' : '"';+            accum.append(' ').append(quote).append(systemId).append(quote);+        }         if (attributes().hasKey(InternalSubsetKey)) // only if via the xml parser; html parser will drop             accum.append(" [").append(attr(InternalSubsetKey)).append(']');         accum.append('>');src/test/java/org/jsoup/nodes/DocumentTypeTest.javaindex b4a5b8d4..0c9207a5 100644@@ -72,6 +72,15 @@ public class DocumentTypeTest {         assertEquals(emptySubset, xmlOutput(emptySubset));     } +    @Test void systemIdentifierUsesSafeQuote() {+        // use a delimiter that does not occur in the system identifier+        String doubleQuote = "<!DOCTYPE root SYSTEM 'a\"b.dtd'>";+        assertEquals(doubleQuote, xmlOutput(doubleQuote));++        String singleQuote = "<!DOCTYPE root SYSTEM \"a'b.dtd\">";+        assertEquals(singleQuote, xmlOutput(singleQuote));+    }+     private String htmlOutput(String in) {         DocumentType type = (DocumentType) Jsoup.parse(in).childNode(0);         return type.outerHtml();