简体   繁体   English

Jsoup从字符串中获取Element的最佳方法

[英]Jsoup best method to get an Element from a string

How can I obtain a Jsoup Element from a String? 如何从字符串中获取Jsoup元素? 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. 目前我使用Jsoup.parse(..)方法转换Document中的String,然后将该文档的主体作为Element。 Is there a direct method? 有直接的方法吗?

You can use the XML-Parser instead the HTML one: 您可以使用XML-Parser而不是HTML:

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. 作为对已接受答案的说明,对于我的用例,使用xmlParser搞砸了一些'>'文字(内联样式标记)实例,将它们更改为HTML字符串实体。

It seems that using Parser.htmlParser() may be a better option in some cases, and the result can cast to Element. 在某些情况下,似乎使用Parser.htmlParser()可能是更好的选择,结果可以转换为Element。

Element element = Jsoup.parse(html, "", Parser.htmlParser());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM