How can I obtain a Jsoup Element from a String? For example if I have a String
String myDiv = "<div>Hello jsoup world</div>";
that I want to convert in an Element. Currently I convert the String in a Document with the Jsoup.parse(..) method and then I get the body of that document as Element. Is there a direct method?
You can use the XML-Parser instead the HTML one:
final String html = "<div>Hello jsoup world</div>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
Element tag = doc;
Or shorter:
Element tag = Jsoup.parse(html, "", Parser.xmlParser());
As a note to the accepted answer, for my use case, using the xmlParser messed up some instances of '>' literals (inline style tag), changing them into HTML string entities.
It seems that using Parser.htmlParser() may be a better option in some cases, and the result can cast to Element.
Element element = Jsoup.parse(html, "", Parser.htmlParser());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.