2017-02-01 15 views
0

私はhtmlコードを含む文字列を持っており、その中から特定の要素のみを抽出したいと思います。AndroidでHTMLを解析するためのXmlPullParserまたはJSoup

私はしばらくの間、Googleとスタックのオーバーフローを眺めていましたが、Android XmlPullParserまたはJSoupを使用することをおすすめします。

これらの方法のどれがAndroidでhmtlを解析するのが最適なのですか?その理由は何ですか?

+0

コードや文字列を投稿してください! –

+0

@ GiovanniTerlingen私の弦は何が重要ですか?これは、Webページのhtmlソースコードを含む文字列です。 – Tirafesi

答えて

1

JSOUPは、HTML要素を簡単に識別し、それらからオブジェクトを簡単に作成できるため、明白な選択です。最後に、必要な操作を行い、ドキュメントを文字列に変換し、最後にビューに設定することができます。

以下は、私のWebページのヘッダーとフッターを削除してから私のビューに表示する必要があるコードスニペットです。

if(document!=null) { 

       if (document.getElementById("header").getElementById("site-head") != null) { 
        document.getElementById("header").getElementById("site-head").remove(); 
       } 
       if (document.getElementById("footer") != null) { 
        document.getElementById("footer").remove(); 
       } if (document.getElementsByClass("fs-footer-newsletter") != null) { 
        document.getElementsByClass("fs-footer-newsletter").remove(); 
       } 
       String modifiedDocument = document.toString(); 
       modifiedDocument = modifiedDocument.replace("<html lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\" class=\"no-js\">","<html lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\" class=\"no-js\" style=\"margin-top:0 !important;\">"); 
       modifiedDocument = modifiedDocument.replace("<header id=\"header\">","<header id=\"header\" style=\"margin-top:-16px;\">"); 
       modifiedDocument = modifiedDocument.replace("<ul class=\"main-filters\">","<ul class=\"main-filters\" style=\"top:0;\">"); 
       Document d = Jsoup.parse(modifiedDocument); 
       WebSettings ws = getItemWebview.getSettings(); 
       ws.setJavaScriptEnabled(true); 
       Log.i("modifiedDocument",document.toString()); 
       if(isURLForShop) { 
        loadingImg.setVisibility(View.GONE); 
        getItemWebview.loadDataWithBaseURL(storeUrl, d.toString(), "text/html", "utf-8", ""); 
       }else{ 
        loadingImg.setVisibility(View.GONE); 
        getItemWebview.loadDataWithBaseURL(restyleDenimURL, d.toString(), "text/html", "utf-8", ""); 
       } 
      } 
+0

ありがとうございます。また、JSoupを使用してURLからhtmlコードを直接取得できることもわかったので、HTML文字列を取得する方法を単純化しています。D – Tirafesi

+0

完了:p私はtimelimit – Tirafesi

関連する問題