I was looking int开发者_C百科o many HTML parser for android. I tried many libraries. Can anyone please show me an example how to do it. I want to extract the content of each tag. Please help. I am stuck with this.
Please look at this list. Actually, it's lots of options outside there. For instance, I chose HtmlCleaner library for implementation. Below is an example of usage:
Project structure:
Actual source code:
public class HtmlHelper {
TagNode rootNode;
public HtmlHelper(URL htmlPage) throws IOException
{
HtmlCleaner cleaner = new HtmlCleaner();
rootNode = cleaner.clean(htmlPage);
}
List<TagNode> getLinksByClass(String CSSClassname)
{
List<TagNode> linkList = new ArrayList<TagNode>();
TagNode linkElements[] = rootNode.getElementsByName("a", true);
for (int i = 0; linkElements != null && i < linkElements.length; i++)
{
String classType = linkElements[i].getAttributeByName("class");
if (classType != null && classType.equals(CSSClassname))
{
linkList.add(linkElements[i]);
}
}
return linkList;
}
}
public class StackParser extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.parse);
button.setOnClickListener(myListener);
}
private ProgressDialog pd;
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
pd = ProgressDialog.show(StackParser.this, "Working...", "request to server", true, false);
new ParseSite().execute("http://www.stackoverflow.com");
}
};
private class ParseSite extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... arg) {
List<String> output = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("question-hyperlink");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return output;
}
protected void onPostExecute(List<String> output) {
pd.dismiss();
ListView listview = (ListView) findViewById(R.id.listViewData);
listview.setAdapter(new ArrayAdapter<String>(StackParser.this, android.R.layout.simple_list_item_1 , output));
}
}
}
精彩评论