Skip to content

Commit

Permalink
Don't try to get child nodes if there aren't any yet
Browse files Browse the repository at this point in the history
Fixes #2266
  • Loading branch information
jhy committed Jan 28, 2025
1 parent 8086b1e commit 5d31cac
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
special tags. [2258](https://github.com/jhy/jsoup/issues/2258)
* An `:nth-child` selector with a negative digit-less step, such as `:nth-child(-n+2)`, would be parsed incorrectly as a
positive step, and so would not match as expected. [1147](https://github.com/jhy/jsoup/issues/1147)
* Calling `doc.charset(charset)` on an empty XML document would throw an
`IndexOutOfBoundsException`. [2266](https://github.com/jhy/jsoup/issues/2266)

## 1.18.3 (2024-Dec-02)

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jsoup/nodes/Document.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public Document(String baseUri) {
}

/**
Create a valid, empty shell of a document, suitable for adding more elements to.
Create a valid, empty shell of an HTML document, suitable for adding more elements to.
@param baseUri baseUri of document
@return document with html, head, and body elements.
*/
Expand Down Expand Up @@ -326,7 +326,7 @@ private void ensureMetaCharsetElement() {
}

private XmlDeclaration ensureXmlDecl() {
Node node = ensureChildNodes().get(0);
Node node = firstChild();
if (node instanceof XmlDeclaration) {
XmlDeclaration decl = (XmlDeclaration) node;
if (decl.name().equals("xml")) return decl;
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/org/jsoup/nodes/DocumentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,17 @@ private Document createXmlDocument(String version, String charset, boolean addDe
return doc;
}

@Test void charsetOnEmptyDoc() {
Document xml = new Document(Parser.NamespaceXml, "https://example.com"); // no nodes
xml.outputSettings().syntax(Syntax.xml);
xml.charset(StandardCharsets.UTF_8);
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xml.html());

Document html = new Document("https://example.com");
html.charset(StandardCharsets.UTF_8);
assertEquals("<html><head><meta charset=\"UTF-8\"></head></html>", TextUtil.stripNewlines(html.html()));
}

@Test
public void testShiftJisRoundtrip() throws Exception {
String input =
Expand Down

0 comments on commit 5d31cac

Please sign in to comment.