如何正确解析div块中的文本?

问题描述:

我正在使用我自己的Android应用程序,并且我是解析中的新手。我有网站,我有这样的代码块。如何正确解析div块中的文本?

<div class="row"> 
<div class="col-xs-12" style="margin:0.5em 0;line-height:1.785em"> 
    some text <br> some text <br> some text 
</div> </div> 

我想把这个文本,并把它给在屏幕上的TextView。所以我为AsyncTask编写了这个代码,但它不起作用。

class NewPostsAsyncTask extends AsyncTask<Void, Void, Void> { 

    private String title; // Тут храним значение заголовка сайта 
    private String pst; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     progressDialog = new ProgressDialog(MainActivity.this); 
     progressDialog.setTitle("Новые"); 
     progressDialog.setMessage("Загрузка..."); 
     progressDialog.setIndeterminate(false); 
     progressDialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 

     Document doc = null; // Здесь хранится будет разобранный html документ 
     try { 
      doc = Jsoup.connect(URL).get(); // Считываем заголовок страницы 

      // Using Elements to get the Meta data 
      Elements post = doc.select("div[class=col-xs-12]"); 
      // Locate the content attribute 
      pst = post.attr("[style=margin:0.5em 0;line-height:1.785em]"); 

     } catch (IOException e) { 
      e.printStackTrace(); // Если не получилось считать 
     } 

     // Если всё считалось, то вытаскиваем из считанного html документа заголовок 
     if (doc != null) 
      title = doc.title(); 
     else 
      title = "Ошибка"; 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 

     //websitePost.setText(title); 
     websitePost.setText(pst); 
     progressDialog.dismiss(); 
    } 
} 

你能解释一下我该怎么做,你能告诉我我的错误吗?

P. S.对不起,如果我的英语不好。

+0

你应该添加@DreadfulWeather我没有例外的例外或输出什么 – DreadfulWeather

+0

,因为它工作正常,但我还没有对TextView的输出。 – Kostya

+0

你能选择你想要使用该选择器的元素吗?如果是这样的话,请使用你的元素上的text()方法检查字符串 – DreadfulWeather

IIRC你没有引用你的用例的正确元素。你应该引用post.text()

... 
// Using Elements to get the Meta data 
Elements post = doc.select("div[class=col-xs-12]"); 
// Locate the content attribute 
pst = post.text(); 
... 

为什么不使用this而不是做所有的解析?

aTextView.setText(Html.fromHtml(yourHtmlString)); 
+0

感谢您的链接,我会阅读有关此。 – Kostya