I am using jsoup in my android app to parse my html code but now I need parse table data and I can not get it to work. I try many ways but not successful so I want try luck here if anyone have experience.

Here is part of my html:

<div id="editacia_jedla">
    <h2>My header</h2>
    <h3>My sub header</h3>

    <table border="0" class="jedalny_listok_tabulka" cellpadding="2" cellspacing="1">
    <tr>
        <td width="100" class="menu_nazov neparna" align="left">Food Menu 1</td>
        <td class="jedlo neparna" align="left">vegetable and beef
        <div class="jedlo_box_alergeny">Allergens: <a href="#" class="alergen_1">1</a>, <a href="#" class="alergen_3">3</a></div>
        </td>
    </tr>
    <tr>
        <td width="100" class="menu_nazov parna" align="left">Food Menu 2</td>
        <td class="jedlo parna" align="left">Potato salad and pork
        <div class="jedlo_box_alergeny">Allergens: <a href="#" class="alergen_6">6</a></div>
        </td>
    </tr>
    </table>  
    etc
</div>

My java/android code:

try {
            String tableHtmlCode="";
            Document fullHtmlDocument = Jsoup.connect(urlOfFoodDay).get();
            Element elm1 = fullHtmlDocument.select("#editacia_jedla").first();
            for( Element element : elm1.children() )
            {
                tableHtmlCode+=element.getElementsByIndexEquals(2); //this set table content because 0=h2, 1=h3
            }
            Document parsedTableDocument = Jsoup.parse(tableHtmlCode);
            //Element th = parsedTableDocument.select("td[class=jedlo neparna]").first();  THIS IS BAD
            String foodContent="";
            String foodAllergens="";
        }

So now I want extract text vegetable and beef and save it to string foodContent and numbera 1, 3(together) from div class jedlo_box_alergeny save to string foodAllergens. Someone can help? I will very grateful for any ideas

有帮助吗?

解决方案

Iterate over your document's parent tag jedalny_listok_tabulka and loop over td tags.

td tag is the parent to href tags which include the allergy values. Hence, you would loop over the tags a elements to get your numbers, something like:

Elements myElements = doc.getElementsByClass("jedalny_listok_tabulka")
                .first().getElementsByTag("td");
        for (Element element : myElements) {
            if (element.className().contains("jedlo")) {
                String foodContent = element.ownText();
                String foodAllergen = "";

                for (Element href : element.getElementsByTag("a")) {
                    foodAllergen += " " + href.text();
                }

                System.out.println(foodContent + " : " + foodAllergen);
            }
        }

Output:

vegetable and beef :  1 3
Potato salad and pork :  6
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top