你如何在android中解析HTML?

MCH*_*ALL 5 html xml parsing android

我正在为android制作一个应用程序,该应用程序功能的一个元素是返回来自在线搜索库目录的结果.应用程序需要以与应用程序其余部分保持一致的方式显示搜索结果,该搜索结果通过自定义HTML表单执行.即,需要解析搜索结果并显示有用的元素.我只是想知道是否/如何在Android中实现这一目标?

yos*_*i24 15

你会使用Html Parser.我使用和工作非常好的一个是JSoup 这是你需要从解析html开始的地方.此外阿帕奇杰里科是个不错的选择.

您将使用DOM检索html文档,并使用JSOUP Select()方法选择您想要获取的任何标记.通过标签,ID或类.

Use the: Jsoup.connect(String url) method:

 Document doc = Jsoup.connect("http://example.com/").get();
Run Code Online (Sandbox Code Playgroud)

这将允许您使用URL连接到html页面.并将其存储为Document doc,通过DOM.并使用selector()方法从中读取.

描述

connect(String url)方法创建一个新的Connection,get()获取并解析一个HTML文件.如果在获取URL时发生错误,它将抛出IOException,您应该适当地处理它.

Connection接口设计用于方法链接以构建特定请求:

 Document doc = Jsoup.connect("http://example.com")
Run Code Online (Sandbox Code Playgroud)

如果您阅读有关Jsoup的文档,您应该能够实现这一目标.

编辑:这是你如何使用选择器方法

  //Once the Document is retrieved above, use these selector methods to Extract the   data you want by using the tags, id, or css class 

  Elements links = doc.select("a[href]"); // a with href
  Elements pngs = doc.select("img[src$=.png]");
  // img with src ending .png

  Element masthead = doc.select("div.masthead").first();
  // div with class=masthead

  Elements resultLinks = doc.select("h3.r > a"); // direct a after h3
Run Code Online (Sandbox Code Playgroud)

编辑:使用JSOUP你可以使用它来获取属性,文本,

Document doc = Jsoup.connect("http://example.com")
Element link = doc.select("a").first();

String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""

String linkOuterH = link.outerHtml(); 
// "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"
Run Code Online (Sandbox Code Playgroud)


Com*_*Man 5

您可以使用 XmlPullParser 来解析 XML。

例如参考http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

  • HTML 不是 XML,尤其是 HTML5,它带有诸如 &lt;br&gt; 之类的自闭合标签。我永远不会用 XML 解析器来解析它。 (3认同)