Android使用Jsoup解析Html表格的方法
本文实例讲述了Android使用Jsoup解析Html表格的方法。分享给大家供大家参考,具体如下:
看代码吧,可解析表中的labeltextbutton自己根据需要再添加,呵呵
importjava.util.ArrayList; importjava.util.List; importorg.apache.http.NameValuePair; importorg.apache.http.message.BasicNameValuePair; importorg.jsoup.Jsoup; importorg.jsoup.nodes.Document; importorg.jsoup.nodes.Element; importorg.jsoup.select.Elements; importandroid.app.Activity; importandroid.graphics.Color; importandroid.os.Bundle; importandroid.view.View; importandroid.view.ViewGroup; importandroid.view.Window; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.TableLayout; importandroid.widget.TableRow; importandroid.widget.TextView; importandroid.widget.Toast; publicclassTableParseActivityextendsActivity{ privateDocumentdoc; privateStringhtml=null; privateTableLayouttableLayout; privatefinalintWC=ViewGroup.LayoutParams.WRAP_CONTENT; privatefinalintFP=ViewGroup.LayoutParams.FILL_PARENT; privatefinalintWIDTH=80; privateStringfunctionName,fields; privateList<NameValuePair>params; privatestaticStringurl; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.analyzing); html="需要解析的HTML字符串"; tableParse(); } publicvoidtableParse(){ doc=Jsoup.parse(html); Elementstrs=doc.select("tr"); tableLayout=(TableLayout)findViewById(R.id.tableLayout1); TableLayout.LayoutParamsp=newTableLayout.LayoutParams(FP,WC); this.setTitle(doc.title()); for(Elementrow:trs){//循环表下的行tr对象 TableRowtableRow=newTableRow(this); Elementscols=row.children(); for(Elementcol:cols){//循环行下的列td对象 Elementschildren=col.children(); for(Elementchild:children){ if(child.tagName().equals("label")){ TextViewtextView=newTextView(this); textView.setText(child.val()); textView.setTextColor(Color.BLACK); tableRow.addView(textView); }elseif(child.tagName().equals("input")&&child.attributes().get("type").equals("text")){ EditTexteditText=newEditText(this); editText.setText(child.val()); editText.setWidth(WIDTH); tableRow.addView(editText); Stringid=child.attributes().get("id"); if(id.length()>0){ editText.setId(Integer.parseInt(child.attributes().get("id"))); } }elseif(child.tagName().equals("input")&&child.attributes().get("type").equals("button")){ Buttonbutton=newButton(this); button.setText(child.val()); tableRow.addView(button); fields=child.attributes().get("fields"); functionName=child.attributes().get("functionName"); button.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ //TODOonClick } }); }//endif(child.tagName().equals("input")&&child.attributes().get("type").equals("button")) }//endfor(Elementchild:children) }//endfor(Elementcol:cols) tableLayout.addView(tableRow,p); }//endfor(Elementrow:rows) }//endtableParse() }
希望本文所述对大家Android程序设计有所帮助。