Skip to content

Commit

Permalink
Merge pull request #2844 from sparklemotion/2808-java-first-element-c…
Browse files Browse the repository at this point in the history
…hild-npe

fix(jruby): first_element_child properly returns nil
  • Loading branch information
flavorjones committed Apr 8, 2023
2 parents 0c1ee6b + 46dd3e2 commit f671857
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions ext/java/nokogiri/XmlNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -762,14 +762,14 @@ public class XmlNode extends RubyObject
if (children.getLength() == 0) {
return Collections.emptyList();
}
ArrayList<Node> elements = firstOnly ? null : new ArrayList<Node>(children.getLength());
ArrayList<Node> elements = new ArrayList<Node>();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
elements.add(child);
if (firstOnly) {
return Collections.singletonList(child);
return elements;
}
elements.add(child);
}
}
return elements;
Expand Down
10 changes: 10 additions & 0 deletions test/xml/test_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def test_first_element_child
assert_predicate(node, :element?, "node is an element")
end

def test_first_element_child_with_no_match
doc = Nokogiri::XML::Document.parse("<root>asdf</root>")
assert_nil(doc.root.first_element_child)
end

def test_element_children
nodes = xml.root.element_children
assert_equal(xml.root.first_element_child, nodes.first)
Expand All @@ -27,6 +32,11 @@ def test_last_element_child
assert_equal(nodes.last, xml.root.element_children.last)
end

def test_last_element_child_with_no_match
doc = Nokogiri::XML::Document.parse("<root>asdf</root>")
assert_nil(doc.root.last_element_child)
end

def test_bad_xpath
bad_xpath = "//foo["

Expand Down

0 comments on commit f671857

Please sign in to comment.