Skip to content

Commit

Permalink
fix jhy#1411
Browse files Browse the repository at this point in the history
  • Loading branch information
suarez12138 committed Apr 24, 2021
1 parent ae9a18c commit a882803
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/main/java/org/jsoup/nodes/Element.java
Original file line number Diff line number Diff line change
Expand Up @@ -1621,6 +1621,22 @@ public Element html(String html) {
return this;
}

/**
* Create an element with HTML.
* @param html HTML to parse, there should be only one outer tag which become the return element.
* @return the element create by the outer tag
* @see #html(String)
*/
static Element of(final String html){
Element e = new Element("div").html(html);
if (e.childNodeSize() > 1){
throw new IllegalArgumentException("Element syntax error: Number of outer element must be one.");
}else if (e.childNodeSize() == 0){
throw new IllegalArgumentException("Element syntax error: No legal element detected.");
}
return e.child(0);
}

@Override
public Element clone() {
return (Element) super.clone();
Expand Down
21 changes: 21 additions & 0 deletions src/test/java/org/jsoup/nodes/ElementTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2039,4 +2039,25 @@ public void childNodesAccessorDoesNotVivify() {
els.add(new Element("a"));
assertEquals(1, els.size());
}

@Test
public void elementOf01() {
assertThrows(IllegalArgumentException.class,()->{
Element e = Element.of("<span>Some stuff</span><span>Second part</span>");
});
}

@Test
public void elementOf02() {
Element e = Element.of("<div id=\"test\"><span>Some stuff</span><span>Second part</span></div>");
assertEquals("div",e.tag().getName());
assertEquals("test",e.attributes().get("id"));
}

@Test
public void elementOf03() {
assertThrows(IllegalArgumentException.class,()->{
Element e = Element.of("");
});
}
}

0 comments on commit a882803

Please sign in to comment.