Backtestsjsouprun-20261006-181938#2572
W3CDom drops some XML node types
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches convert CDataNode to CDATASection, convert `<?...?>` nodes other than `xml` to ProcessingInstruction, and walk the document's children so comments and PIs outside the root are kept.
Patch A changes less of the existing code. Doctype creation stays where it was, at document creation. A tracks whether a node came before the doctype and moves it in front when needed, so document order holds. It resets `builder.dest = out` before each top-level traverse, which avoids changing the delicate `tail` ascend logic. PI detection uses the real `isDeclaration` flag, exposed through NodeInternals, so `<!ENTITY>` declarations are excluded reliably.
Patch B is riskier:
- It removes doctype creation from `fromJsoup` and recreates the doctype only during whole-document traversal. As a result, `fromJsoup(Element)`, which previously got the owner document's doctype, silently loses it. That is a behavioural regression outside the issue's scope.
- It widens the `tail` ascend condition from `getParentNode() instanceof Element` to `!= null`. That logic exists to handle elements emitted as text, so the change adds risk.
- It detects PIs with `outerHtml().startsWith("<?")`, which is fragile and costly compared with using the flag.
- Its CDATA fallback is harmless.
On tests, Patch A is clearly stronger. It checks the exact child sequence and count at document level, ordering around a doctype, PIs inside elements, exclusion of the XML declaration and markup declarations, the source user data link, CDATA in both XML and HTML (SVG), subtree conversion, and serialized output. Patch B's three tests are thinner and do not check full child counts or exclusion of declarations.
Patch A is the safer and better-tested 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
14m 49s
Wall-clock time in the container
Full test suite
No new failures
2,166 passed · 0 skipped · 2,166 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
181vs 115 merged
Changed lines, ours vs merged
The issue
View on GitHubW3CDom.fromJsoup(...) currently drops XML processing instructions and comments outside the root element, and converts CDataNode instances to ordinary text nodes.
All three have direct W3C DOM equivalents, so conversion should preserve them and their document order. XML declarations and doctype internal subsets remain out of scope.
The two patches
CHANGES.mdindex f697d8da..1ee6c6bd 100644@@ -12,6 +12,7 @@ * Aligned the XML parser stack depth and lookups to the configured maximum, which now defaults to 512 for both HTML and XML. ### Bug Fixes+* `W3CDom` now preserves XML processing instructions (inside and outside the root element), comments outside the root element, and CDATA sections (as `CDATASection` nodes, rather than plain text), in document order. The `<?xml ...?>` declaration and `<!...>` markup declarations are still not converted. * Fixed `W3CDom` namespace conversion in several cases: [#2559](https://github.com/jhy/jsoup/pull/2559) * Namespace declarations and prefixed attributes now carry the correct namespace URI, so namespace-aware DOM lookups work as expected. * Attributes added after parsing, or included through subtree conversion, now use inherited prefix declarations.src/main/java/org/jsoup/helper/W3CDom.javaindex cc117e44..ef8f865b 100644@@ -4,9 +4,11 @@ import org.jsoup.internal.NamespaceBindings; import org.jsoup.internal.StringUtil; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes;+import org.jsoup.nodes.NodeInternals; import org.jsoup.parser.Parser; import org.jsoup.select.NodeVisitor; import org.jsoup.select.Selector;+import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation;@@ -15,6 +17,7 @@ import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList;+import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.jspecify.annotations.Nullable; @@ -256,9 +259,41 @@ public class W3CDom { } builder.syntax = inDoc.outputSettings().syntax(); }- org.jsoup.nodes.Element rootEl = in instanceof org.jsoup.nodes.Document ? in.firstElementChild() : in; // skip the #root node if a Document- assert rootEl != null;- builder.traverse(rootEl);+ if (in instanceof org.jsoup.nodes.Document) {+ // skip the #root node, converting the root element and its comment and processing instruction siblings in order+ org.jsoup.nodes.Element rootEl = in.firstElementChild();+ assert rootEl != null;+ // the doctype was already added at creation; nodes that precede it in the source are moved in front of it+ org.w3c.dom.DocumentType outDoctype = out.getDoctype();+ org.jsoup.nodes.DocumentType inDoctype = ((org.jsoup.nodes.Document) in).documentType();+ boolean beforeDoctype = outDoctype != null && inDoctype != null;+ for (org.jsoup.nodes.Node child : in.childNodes()) {+ if (child == inDoctype) {+ beforeDoctype = false;+ } else if (child == rootEl || isDocumentLevelMisc(child)) {+ Node last = out.getLastChild();+ builder.dest = out;+ builder.traverse(child);+ Node added = out.getLastChild();+ if (beforeDoctype && added != last)+ out.insertBefore(added, outDoctype);+ }+ // other document-level nodes (doctype, whitespace text, xml declaration, extra elements) are not converted+ }+ } else {+ builder.traverse(in);+ }+ }++ /** Tests if a document-level node has a W3C equivalent that may sit beside the root element. */+ private static boolean isDocumentLevelMisc(org.jsoup.nodes.Node node) {+ return node instanceof org.jsoup.nodes.Comment ||+ (node instanceof org.jsoup.nodes.XmlDeclaration && isConvertibleProcessingInstruction((org.jsoup.nodes.XmlDeclaration) node));+ }++ /** Processing instructions are converted; the {@code <?xml ...?>} declaration and {@code <!...>} declarations are not. */+ private static boolean isConvertibleProcessingInstruction(org.jsoup.nodes.XmlDeclaration decl) {+ return NodeInternals.isProcessingInstruction(decl) && !decl.name().equalsIgnoreCase("xml"); } /**@@ -389,6 +424,10 @@ public class W3CDom { if (sourceEl == contextElement) doc.setUserData(ContextNodeProperty, el, null); dest = el; // descend+ } else if (source instanceof org.jsoup.nodes.CDataNode) {+ org.jsoup.nodes.CDataNode sourceCData = (org.jsoup.nodes.CDataNode) source;+ CDATASection cdata = doc.createCDATASection(sourceCData.getWholeText());+ append(cdata, sourceCData); } else if (source instanceof org.jsoup.nodes.TextNode) { org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source; Text text = doc.createTextNode(sourceText.getWholeText());@@ -401,6 +440,16 @@ public class W3CDom { org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source; Text node = doc.createTextNode(sourceData.getWholeData()); append(node, sourceData);+ } else if (source instanceof org.jsoup.nodes.XmlDeclaration) {+ org.jsoup.nodes.XmlDeclaration sourceDecl = (org.jsoup.nodes.XmlDeclaration) source;+ if (!isConvertibleProcessingInstruction(sourceDecl)) return;+ ProcessingInstruction pi;+ try {+ pi = doc.createProcessingInstruction(sourceDecl.name(), sourceDecl.getWholeDeclaration());+ } catch (DOMException ignored) {+ return; // target is not a valid XML name; no W3C representation, so dropped (as for invalid doctypes)+ }+ append(pi, sourceDecl); } else { // unhandled. note that doctype is not handled here - rather it is used in the initial doc creation }src/main/java/org/jsoup/nodes/NodeInternals.javaindex 7063dd9e..8ca451a7 100644@@ -11,6 +11,14 @@ import org.jsoup.internal.LineMap; public final class NodeInternals { private NodeInternals() {} + /**+ Tests if an XmlDeclaration is a processing instruction ({@code <?...?>}) rather than a declaration ({@code <!...>}).+ */+ public static boolean isProcessingInstruction(XmlDeclaration decl) {+ Validate.notNull(decl);+ return decl.isProcessingInstruction();+ }+ /** Sets the source range for a node's start. */src/main/java/org/jsoup/nodes/XmlDeclaration.javaindex d9fbef50..d7adce7e 100644@@ -25,6 +25,11 @@ public class XmlDeclaration extends LeafNode { this.isDeclaration = isDeclaration; } + /** Tests if this is a processing instruction ({@code <?...?>}), rather than a declaration ({@code <!...>}). */+ boolean isProcessingInstruction() {+ return !isDeclaration;+ }+ @Override public String nodeName() { return "#declaration"; }src/test/java/org/jsoup/helper/W3CDomTest.javaindex ae65b25a..9ba4c06f 100644@@ -10,9 +10,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource;+import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList;+import org.w3c.dom.ProcessingInstruction; import org.xml.sax.InputSource; import javax.xml.XMLConstants;@@ -29,6 +31,7 @@ import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets;+import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.stream.Stream;@@ -755,6 +758,115 @@ public class W3CDomTest { assertEquals(0, w3CDoc.getElementsByTagName("xml:thing").getLength()); } + @Test void preservesDocumentLevelCommentsAndProcessingInstructions() {+ String xml = "<?xml version=\"1.0\"?>\n<!-- before --><?xml-stylesheet href=\"style.xsl\" type=\"text/xsl\"?>\n<root><a/></root>\n<!-- after --><?tail data?>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());+ Document w3Doc = new W3CDom().fromJsoup(jdoc);++ NodeList children = w3Doc.getChildNodes();+ assertEquals(5, children.getLength());+ assertEquals(Node.COMMENT_NODE, children.item(0).getNodeType());+ assertEquals(" before ", children.item(0).getNodeValue());+ assertEquals(Node.PROCESSING_INSTRUCTION_NODE, children.item(1).getNodeType());+ ProcessingInstruction stylesheet = (ProcessingInstruction) children.item(1);+ assertEquals("xml-stylesheet", stylesheet.getTarget());+ assertEquals("href=\"style.xsl\" type=\"text/xsl\"", stylesheet.getData());+ assertEquals(Node.ELEMENT_NODE, children.item(2).getNodeType());+ assertSame(w3Doc.getDocumentElement(), children.item(2));+ assertEquals("root", children.item(2).getNodeName());+ assertEquals(Node.COMMENT_NODE, children.item(3).getNodeType());+ assertEquals(" after ", children.item(3).getNodeValue());+ ProcessingInstruction tail = (ProcessingInstruction) children.item(4);+ assertEquals("tail", tail.getTarget());+ assertEquals("data", tail.getData());++ org.jsoup.nodes.XmlDeclaration jStylesheet = jdoc.childNodes().stream()+ .filter(n -> n instanceof org.jsoup.nodes.XmlDeclaration && ((org.jsoup.nodes.XmlDeclaration) n).name().equals("xml-stylesheet"))+ .map(n -> (org.jsoup.nodes.XmlDeclaration) n).findFirst().orElseThrow(IllegalStateException::new);+ assertSame(jStylesheet, stylesheet.getUserData(W3CDom.SourceProperty));+ assertEquals(1, w3Doc.getDocumentElement().getChildNodes().getLength()); // nothing misplaced into the root++ String out = W3CDom.asString(w3Doc, W3CDom.OutputXml());+ assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!-- before --><?xml-stylesheet href=\"style.xsl\" type=\"text/xsl\"?><root><a/></root><!-- after --><?tail data?>", out);+ }++ @Test void preservesOrderOfCommentsAndProcessingInstructionsAroundDoctype() {+ String xml = "<!-- first --><?pi one?><!DOCTYPE root SYSTEM \"root.dtd\"><!-- second --><root/>";+ Document w3Doc = new W3CDom().fromJsoup(Jsoup.parse(xml, "", Parser.xmlParser()));+ NodeList children = w3Doc.getChildNodes();+ assertEquals(5, children.getLength());+ assertEquals(" first ", children.item(0).getNodeValue());+ assertEquals("pi", ((ProcessingInstruction) children.item(1)).getTarget());+ assertSame(w3Doc.getDoctype(), children.item(2));+ assertEquals(" second ", children.item(3).getNodeValue());+ assertSame(w3Doc.getDocumentElement(), children.item(4));+ }++ @Test void preservesProcessingInstructionInsideElement() {+ String xml = "<root><a>One</a><?target some data?><b/></root>";+ Document w3Doc = new W3CDom().fromJsoup(Jsoup.parse(xml, "", Parser.xmlParser()));+ NodeList children = w3Doc.getDocumentElement().getChildNodes();+ assertEquals(3, children.getLength());+ ProcessingInstruction pi = (ProcessingInstruction) children.item(1);+ assertEquals("target", pi.getTarget());+ assertEquals("some data", pi.getData());+ assertEquals("b", children.item(2).getNodeName());+ assertEquals("<root><a>One</a><?target some data?><b/></root>", W3CDom.asString(w3Doc, Collections.singletonMap(OutputKeys.OMIT_XML_DECLARATION, "yes")));+ }++ @Test void doesNotConvertXmlDeclarationOrMarkupDeclarations() {+ String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!ENTITY foo \"bar\"><root/>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());+ Document w3Doc = new W3CDom().fromJsoup(jdoc);+ NodeList children = w3Doc.getChildNodes();+ assertEquals(1, children.getLength());+ assertSame(w3Doc.getDocumentElement(), children.item(0));+ }++ @Test void convertsCDataNodesToCDataSections() {+ String xml = "<root><a>One <![CDATA[<two> & three]]> four</a></root>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());+ Document w3Doc = new W3CDom().fromJsoup(jdoc);+ NodeList children = w3Doc.getElementsByTagName("a").item(0).getChildNodes();+ assertEquals(3, children.getLength());+ assertEquals(Node.TEXT_NODE, children.item(0).getNodeType());+ assertEquals(Node.CDATA_SECTION_NODE, children.item(1).getNodeType());+ CDATASection cdata = (CDATASection) children.item(1);+ assertEquals("<two> & three", cdata.getData());+ assertSame(jdoc.expectFirst("a").childNode(1), cdata.getUserData(W3CDom.SourceProperty));+ assertEquals(Node.TEXT_NODE, children.item(2).getNodeType());++ String out = W3CDom.asString(w3Doc, Collections.singletonMap(OutputKeys.OMIT_XML_DECLARATION, "yes"));+ assertEquals("<root><a>One <![CDATA[<two> & three]]> four</a></root>", out);+ }++ @Test void convertsHtmlCDataNodesToCDataSections() {+ String html = "<svg><text><![CDATA[a < b]]></text></svg>";+ Document w3Doc = new W3CDom().fromJsoup(Jsoup.parse(html));+ Node text = w3Doc.getElementsByTagNameNS("*", "text").item(0);+ assertEquals(Node.CDATA_SECTION_NODE, text.getFirstChild().getNodeType());+ assertEquals("a < b", text.getFirstChild().getNodeValue());+ }++ @Test void subtreeConvertIncludesNestedProcessingInstructionsAndCData() {+ String xml = "<!-- outside --><root><a><?pi x?><![CDATA[c]]></a></root>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());+ W3CDom w3c = new W3CDom();+ Document w3Doc = w3c.fromJsoup(jdoc);+ Document subtree;+ try {+ subtree = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();+ } catch (ParserConfigurationException e) {+ throw new IllegalStateException(e);+ }+ w3c.convert(jdoc.expectFirst("a"), subtree);+ assertEquals(1, subtree.getChildNodes().getLength());+ Node a = subtree.getDocumentElement();+ assertEquals(Node.PROCESSING_INSTRUCTION_NODE, a.getFirstChild().getNodeType());+ assertEquals(Node.CDATA_SECTION_NODE, a.getLastChild().getNodeType());+ assertEquals(Node.COMMENT_NODE, w3Doc.getFirstChild().getNodeType());+ }+ private static Stream<Arguments> parserProvider() { return Stream.of( Arguments.of(Parser.htmlParser()),
CHANGES.mdindex f697d8da..ceda0fcb 100644@@ -6,6 +6,7 @@ * Improved consecutive `StreamParser.selectFirst(...)` calls during progressive parsing, so later matches are returned with their parsed contents when earlier selections have left them as parser lookahead. E.g., given `<title>One</title><p id=hit>Full</p><p>Next</p>`, selecting `title` and then `#hit` now advances the partial lookahead and returns `<p id="hit">Full</p>`, rather than returning an empty `<p id="hit"></p>` before its content is parsed. The updated readiness tracking follows StreamParser's normal emission order across implicit HTML structure and parser recovery. [#2551](https://github.com/jhy/jsoup/pull/2551) * Improved XML parser performance and memory use for documents with many nested namespace declarations by recording namespace changes within each element scope. [#2556](https://github.com/jhy/jsoup/pull/2556) * Improved `W3CDom` conversion performance for documents with many nested namespace declarations. The W3C converter now uses the same optimized namespace tracking as the XML parser. [#2559](https://github.com/jhy/jsoup/pull/2559)+* Improved `W3CDom` XML conversion to retain processing instructions, comments outside the root element, and CDATA sections, which were previously dropped or converted to text. [#2572](https://github.com/jhy/jsoup/issues/2572) * DOM mutation methods, including child insertion and replacement, now reject operations that would create a cycle, such as making a node its own child or moving an ancestor beneath a descendant. [#2552](https://github.com/jhy/jsoup/issues/2552) ### Changes@@ -28,7 +29,6 @@ * Fixed parsing of malformed SVG and MathML content so that breakout HTML tags are placed according to the HTML specification. [#2562](https://github.com/jhy/jsoup/issues/2562) * Fixed deeply nested malformed HTML parsing that could lose the document body because stack lookups did not align to the configured maximum parser depth. [#2569](https://github.com/jhy/jsoup/pull/2569) - ## 1.23.1 (2026-Jul-30) ### Improvementssrc/main/java/org/jsoup/helper/W3CDom.javaindex cc117e44..1ec3c2b6 100644@@ -9,7 +9,6 @@ import org.jsoup.select.NodeVisitor; import org.jsoup.select.Selector; import org.w3c.dom.Comment; import org.w3c.dom.DOMException;-import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element;@@ -202,18 +201,8 @@ public class W3CDom { DocumentBuilder builder; try { builder = factory.newDocumentBuilder();- DOMImplementation impl = builder.getDOMImplementation(); Document out = builder.newDocument(); org.jsoup.nodes.Document inDoc = in.ownerDocument();- org.jsoup.nodes.DocumentType doctype = inDoc != null ? inDoc.documentType() : null;- if (doctype != null) {- try {- org.w3c.dom.DocumentType documentType = impl.createDocumentType(doctype.name(), doctype.publicId(), doctype.systemId());- out.appendChild(documentType);- } catch (DOMException ignored) {- // invalid / empty doctype dropped- }- } out.setXmlStandalone(true); // if in is Document, use the root element, not the wrapping document, as the context: org.jsoup.nodes.Element context = (in instanceof org.jsoup.nodes.Document) ? in.firstElementChild() : in;@@ -256,9 +245,10 @@ public class W3CDom { } builder.syntax = inDoc.outputSettings().syntax(); }- org.jsoup.nodes.Element rootEl = in instanceof org.jsoup.nodes.Document ? in.firstElementChild() : in; // skip the #root node if a Document- assert rootEl != null;- builder.traverse(rootEl);+ if (in instanceof org.jsoup.nodes.Document)+ builder.traverseDocument((org.jsoup.nodes.Document) in);+ else+ builder.traverse(in); } /**@@ -363,6 +353,16 @@ public class W3CDom { contextElement = (org.jsoup.nodes.Element) doc.getUserData(ContextProperty); // Track the context jsoup Element, so we can save the corresponding w3c element } + // Traverse only nodes supported as W3C document children, and keep the first element as the root.+ private void traverseDocument(org.jsoup.nodes.Document source) {+ org.jsoup.nodes.Element root = source.firstElementChild();+ for (org.jsoup.nodes.Node child : source.childNodes()) {+ if (child == root || child instanceof org.jsoup.nodes.DocumentType ||+ child instanceof org.jsoup.nodes.Comment || child instanceof org.jsoup.nodes.XmlDeclaration)+ traverse(child);+ }+ }+ @Override public void head(org.jsoup.nodes.Node source, int depth) { if (source instanceof org.jsoup.nodes.Element) {@@ -389,6 +389,10 @@ public class W3CDom { if (sourceEl == contextElement) doc.setUserData(ContextNodeProperty, el, null); dest = el; // descend+ } else if (source instanceof org.jsoup.nodes.DocumentType) {+ appendDocumentType((org.jsoup.nodes.DocumentType) source);+ } else if (source instanceof org.jsoup.nodes.CDataNode) {+ appendCdata((org.jsoup.nodes.CDataNode) source); } else if (source instanceof org.jsoup.nodes.TextNode) { org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source; Text text = doc.createTextNode(sourceText.getWholeText());@@ -401,8 +405,39 @@ public class W3CDom { org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source; Text node = doc.createTextNode(sourceData.getWholeData()); append(node, sourceData);+ } else if (source instanceof org.jsoup.nodes.XmlDeclaration) {+ appendProcessingInstruction((org.jsoup.nodes.XmlDeclaration) source); } else {- // unhandled. note that doctype is not handled here - rather it is used in the initial doc creation+ // unhandled+ }+ }++ // Keep the doctype in document order; invalid doctypes cannot be represented.+ private void appendDocumentType(org.jsoup.nodes.DocumentType source) {+ try {+ DocumentType type = doc.getImplementation().createDocumentType(source.name(), source.publicId(), source.systemId());+ append(type, source);+ } catch (DOMException ignored) {+ // invalid / empty doctype dropped+ }+ }++ // Preserve CDATA where possible; programmatic content may be invalid for a W3C CDATA node.+ private void appendCdata(org.jsoup.nodes.CDataNode source) {+ try {+ append(doc.createCDATASection(source.getWholeText()), source);+ } catch (DOMException ignored) {+ append(doc.createTextNode(source.getWholeText()), source);+ }+ }++ // XmlDeclaration also represents <!name ...> nodes; XML declarations are reserved by the W3C DOM.+ private void appendProcessingInstruction(org.jsoup.nodes.XmlDeclaration source) {+ if (!source.outerHtml().startsWith("<?") || source.name().equalsIgnoreCase("xml")) return;+ try {+ append(doc.createProcessingInstruction(source.name(), source.getWholeDeclaration()), source);+ } catch (DOMException ignored) {+ // invalid programmatic processing instruction dropped } } @@ -433,7 +468,7 @@ public class W3CDom { public void tail(org.jsoup.nodes.Node source, int depth) { // head may emit an unrepresentable element as text without descending, so only ascend from its matching output element if (source instanceof org.jsoup.nodes.Element && dest.getUserData(SourceProperty) == source &&- dest.getParentNode() instanceof Element) {+ dest.getParentNode() != null) { dest = dest.getParentNode(); // undescend } if (source instanceof org.jsoup.nodes.Element) {src/test/java/org/jsoup/helper/W3CDomTest.javaindex ae65b25a..d157431e 100644@@ -715,6 +715,52 @@ public class W3CDomTest { assertSame(root, second.getParentNode()); } + @Test void preservesProcessingInstructions() {+ // preserve both PI positions, but not the XML declaration+ String xml = "<?xml version=\"1.0\"?><?xml-stylesheet type=\"text/xsl\" href=\"style.xsl\"?><root xmlns=\"urn:test\"><?target data?></root>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());++ org.w3c.dom.Document w3cDoc = new W3CDom().fromJsoup(jdoc);+ Node top = w3cDoc.getFirstChild();+ Node child = w3cDoc.getDocumentElement().getFirstChild();++ assertEquals(Node.PROCESSING_INSTRUCTION_NODE, top.getNodeType());+ assertEquals("xml-stylesheet", top.getNodeName());+ assertEquals("type=\"text/xsl\" href=\"style.xsl\"", top.getNodeValue());+ assertNotNull(child);+ assertEquals(Node.PROCESSING_INSTRUCTION_NODE, child.getNodeType());+ assertEquals("target", child.getNodeName());+ assertEquals("data", child.getNodeValue());+ }++ @Test void preservesDocumentLevelComments() {+ // keeps comments, doctype, and root in source order+ String xml = "<!--before--><!DOCTYPE root><root xmlns=\"urn:test\"><child/></root><!--after-->";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());++ org.w3c.dom.Document w3cDoc = new W3CDom().fromJsoup(jdoc);++ assertEquals(Node.COMMENT_NODE, w3cDoc.getFirstChild().getNodeType());+ assertEquals("before", w3cDoc.getFirstChild().getNodeValue());+ assertEquals(Node.DOCUMENT_TYPE_NODE, w3cDoc.getFirstChild().getNextSibling().getNodeType());+ assertSame(w3cDoc.getDocumentElement(), w3cDoc.getFirstChild().getNextSibling().getNextSibling());+ assertEquals(Node.COMMENT_NODE, w3cDoc.getLastChild().getNodeType());+ assertEquals("after", w3cDoc.getLastChild().getNodeValue());+ }++ @Test void preservesCdataSections() {+ // CDATA has a direct W3C node type, so retain it through conversion+ String xml = "<root xmlns=\"urn:test\"><![CDATA[x < y & z]]></root>";+ org.jsoup.nodes.Document jdoc = Jsoup.parse(xml, "", Parser.xmlParser());++ org.w3c.dom.Document w3cDoc = new W3CDom().fromJsoup(jdoc);+ Node child = w3cDoc.getDocumentElement().getFirstChild();++ assertEquals(Node.CDATA_SECTION_NODE, child.getNodeType());+ assertEquals("x < y & z", child.getNodeValue());+ assertTrue(W3CDom.asString(w3cDoc, W3CDom.OutputXml()).contains("<![CDATA[x < y & z]]>"));+ }+ @Test void preservesValidQNameCharacters() { // Unicode letters are valid starts; other valid characters are retained by prepending a safe start String html = "<html xmlns:a='urn:a'><body><div a:é='unicode' a:_b='underscore' a:9b='digit'></div></body></html>";